Missing number in array Python Practise Sheet Question

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
enter image description here

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.

I tried this code but it is not working for all cases.

def MissingNumber(self,array,n):
        
        missingNumber = 0
        for i in range(len(array)):
            if array[i] !=i+1:
                missingNumber = i+1
        
        return missingNumber


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

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

Asked By: Dulip Davi

||

Answers:

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
Answered By: Pratul Pant
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.