Find Missing Number in Array – Python

The task is to identify the missing number in a list of integers that contains N-1 elements, where the integers are in the range from 1 to N. For instance, given the list [1, 2, 4, 5], the missing number is 3.

def find_missing_number(arr):
    n = len(arr) + 1  # Since the array has N-1 elements
    total_sum = n * (n + 1) // 2  # Sum of first N natural numbers
    array_sum = sum(arr)  # Sum of elements in the array
    missing_number = total_sum - array_sum  # The missing number
    return missing_number

# Example usage
example_array = [1, 2, 4, 5]
missing_number = find_missing_number(example_array)
print(f"The missing number is: {missing_number}")

The provided code defines a function find_missing_number that takes an array arr as input. Here’s a breakdown of how it works:

  1. The length of the input array is N-1, so we add 1 to get N, which represents the total count of numbers expected in the range.
  2. We compute the sum of the first N natural numbers using the formula ( \text{total_sum} = \frac{N \times (N + 1)}{2} ). This formula is derived from the arithmetic series sum.
  3. We then calculate the sum of the elements present in the input array using Python’s built-in sum() function.
  4. The missing number can be found by subtracting the array_sum from the total_sum. This difference gives us the number that is absent from the array.
  5. Finally, the function returns the missing number.

In the example provided, when we call find_missing_number with the array [1, 2, 4, 5], the output will be 3, indicating that 3 is the missing number in the sequence. This approach is efficient, operating in O(N) time complexity, and requires O(1) additional space.