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

When working with a sorted array of consecutive numbers that has one missing element, we can use binary search to efficiently find the missing number in O(log n) time complexity.

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

Algorithm

The approach uses binary search with the following logic ?

  • For each element at index i, if no element is missing before it, then A[i] - i should equal A[0]

  • If A[mid] - mid equals A[0], the missing element is in the right half

  • Otherwise, the missing element is in the left half

  • Check adjacent elements to identify the exact missing number

Implementation

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

# Test the function
A = [1, 2, 3, 4, 5, 6, 7, 9]
result = search_missing_item(A)
print(f"Missing element: {result}")
Missing element: 8

Alternative Approach Using Mathematical Formula

For consecutive numbers, we can also use the sum formula to find the missing element ?

def find_missing_simple(A):
    n = len(A)
    first = A[0]
    last = A[-1]
    
    # Expected sum of consecutive numbers from first to last
    expected_sum = (last - first + 1) * (first + last) // 2
    
    # Actual sum of array elements
    actual_sum = sum(A)
    
    return expected_sum - actual_sum

# Test the alternative approach
A = [1, 2, 3, 4, 5, 6, 7, 9]
result = find_missing_simple(A)
print(f"Missing element: {result}")
Missing element: 8

Comparison

Method Time Complexity Space Complexity Best For
Binary Search O(log n) O(1) Large arrays
Mathematical Formula O(n) O(1) Simple implementation

Conclusion

The binary search approach is more efficient for large arrays with O(log n) complexity. The mathematical formula approach is simpler to understand and implement but requires O(n) time to calculate the sum.

Updated on: 2026-03-25T09:47:42+05:30

638 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements