Missing Number in Python


Suppose we have a list of numbers from 0 to n. There is one number that is missing. We have to find the missing number in an efficient approach. So if A = [0, 1, 2, 3, 4, 5, 7, 8, 9], missing number is 6.

To solve this, we will use the binary search approach.

  • sort the list in ascending order
  • high = length of A, and low = 0
  • while low < high, do
    • mid = low + (high – low)/2
    • if A[mid] > mid
      • high = mid
    • otherwise
      • low = mid + 1
  • return low

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def missingNumber(self, nums):
      """
      :type nums: List[int]
      :rtype: int
      """
      nums.sort()
      high = len(nums)
      low = 0
      while low<high:
         mid = low + (high-low)//2
         if nums[mid]>mid:
            high = mid
         else:
            low = mid+1
      return low
ob1 = Solution()
print(ob1.missingNumber([5,3,1,7,8,0,9,2,4]))

Input

nums = [5,3,1,7,8,0,9,2,4]

Output

6

Updated on: 28-Apr-2020

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements