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.

Python provides multiple approaches to solve this problem efficiently. We'll explore three common methods: binary search, mathematical formula, and XOR operation.

Method 1: Using Binary Search

The binary search approach works by comparing array values with their indices after sorting ?

  • Sort the list in ascending order
  • Set high = length of array, and low = 0
  • While low < high, do
    • mid = low + (high − low)/2
    • If A[mid] > mid, then missing number is in left half: high = mid
    • Otherwise, missing number is in right half: low = mid + 1
  • Return low
def missing_number_binary_search(nums):
    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

# Test the function
nums = [5, 3, 1, 7, 8, 0, 9, 2, 4]
result = missing_number_binary_search(nums)
print(f"Missing number: {result}")
Missing number: 6

Method 2: Using Mathematical Formula

Since we know the range is 0 to n, we can use the sum formula to find the missing number ?

def missing_number_sum(nums):
    n = len(nums)
    expected_sum = n * (n + 1) // 2
    actual_sum = sum(nums)
    return expected_sum - actual_sum

# Test the function
nums = [5, 3, 1, 7, 8, 0, 9, 2, 4]
result = missing_number_sum(nums)
print(f"Missing number: {result}")
Missing number: 6

Method 3: Using XOR Operation

XOR has the property that x ^ x = 0 and x ^ 0 = x. We can XOR all numbers and indices ?

def missing_number_xor(nums):
    n = len(nums)
    result = n  # Start with n
    
    for i in range(n):
        result ^= i ^ nums[i]
    
    return result

# Test the function
nums = [5, 3, 1, 7, 8, 0, 9, 2, 4]
result = missing_number_xor(nums)
print(f"Missing number: {result}")
Missing number: 6

Comparison

Method Time Complexity Space Complexity Notes
Binary Search O(n log n) O(1) Requires sorting
Mathematical Sum O(n) O(1) Most intuitive
XOR Operation O(n) O(1) Most efficient

Conclusion

The XOR method is most efficient with O(n) time complexity and no sorting required. The mathematical sum approach is most intuitive, while binary search is useful when the array is already sorted.

Updated on: 2026-03-25T07:14:38+05:30

536 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements