Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Missing number in array Python Practise Sheet Question

I am a student and learning data structures and algorithms. I am unable to solve or short out this GFG question.

Missing number in array

Given an array of size N-1 such that it only contains distinct integers in the range of 1 to N. Find the missing element.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Ques Link

Input:
N = 5
A[] = {1,2,3,5}
Output: 4

Please help me out with the code of the best complexity. Thanks in advance.

>Solution :

I don’t know whether it is the best way to solve this question but here is my code with the O(N) time complexity and O(1) space complexity respectively. Here is my code. Hope this helps you out.

def MissingNumber(self,array,n):
        # The expected sum of the complete array should be ...

        expectedSum = (n*(n+1)) //2
        
        total = 0
        
        for i in array:
            total+=i

        # check the difference between expected sum and actual sum of an array that's the missing number in an array.

        return expectedSum-total
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading