Find Missing Number in Array - Optimal Solution

Find Missing Number in Array - Optimal Solution

Algorithm Steps

  1. Given an array of size N-1, containing unique numbers between 1 to N.
  2. Calculate the sum of the first N natural numbers using the formula N*(N+1)/2.
  3. Calculate the sum of all elements in the given array.
  4. The missing number is the difference between the expected sum and the actual sum.

Find Missing Number in Array - Optimal Solution Code

Python
JavaScript
Java
C++
C
def find_missing_number(arr, N):
    total = N * (N + 1) // 2
    actual_sum = sum(arr)
    return total - actual_sum

# Sample Input
arr = [1, 2, 4, 5, 6]
N = 6
print("Missing Number:", find_missing_number(arr, N))

Detailed Step by Step Example

We are given an array of size 5 containing numbers from 1 to 6 with one number missing.

{ "array": [1,2,4,5,6], "showIndices": true }

Step 1: Calculate the expected sum from 1 to N = 6 * (6 + 1) / 2 = 21.

Step 2: Calculate the actual sum of the array = 18.

Step 3: The missing number is 21 - 18 = 3.

Final Result:

Missing Number = 3