Find missing element in a sorted array of consecutive numbers in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array A of n unique numbers, these n elements are present in the array in ascending order, but there is one missing element. We have to find the missing element.

So, if the input is like A = [1, 2, 3, 4, 5, 6, 7, 9], then the output will be 8.

To solve this, we will follow these steps −

  • n := size of A

  • left := 0

  • right := n - 1

  • mid := 0

  • while right > left , do

    • mid := left +(right - left) / 2

    • if A[mid] - mid is same as A[0], then

      • if A[mid + 1] - A[mid] > 1, then

        • return A[mid] + 1

      • otherwise,

        • left := mid + 1

    • otherwise,

      • if A[mid] - A[mid - 1] > 1, then

        • return A[mid] - 1

      • otherwise,

        • right := mid - 1

  • return -1

Example

Let us see the following implementation to get better understanding −

 Live Demo

def search_missing_item(A):
   n = len(A)
   left, right = 0, n - 1
   mid = 0
   while (right > left):
      mid = left + (right - left) // 2
   if (A[mid] - mid == A[0]):
      if (A[mid + 1] - A[mid] > 1):
         return A[mid] + 1
      else:
         left = mid + 1
      else:
         if (A[mid] - A[mid - 1] > 1):
            return A[mid] - 1
         else:
            right = mid - 1
   return -1

A = [1, 2, 3, 4, 5, 6, 7, 9]
print(search_missing_item(A))

Input

[1, 2, 3, 4, 5, 6, 7, 9]

Output

8
raja
Published on 25-Aug-2020 15:07:46
Advertisements