Python Program to Find Missing Number in Array
total = (n+1)*(n+2)//2 and subtracting the actual sum of array elements with missing = total - sum(arr).Examples
How to Think About It
Algorithm
Code
def find_missing_number(arr): n = len(arr) total = (n + 1) * (n + 2) // 2 missing = total - sum(arr) return missing # Example usage arr = [1, 2, 4, 5, 6] print(find_missing_number(arr))
Dry Run
Let's trace the example array [1, 2, 4, 5, 6] through the code
Calculate length
Length n = 5
Calculate total sum
total = (5 + 1) * (5 + 2) // 2 = 6 * 7 // 2 = 21
Calculate sum of array
sum(arr) = 1 + 2 + 4 + 5 + 6 = 18
Find missing number
missing = total - sum(arr) = 21 - 18 = 3
| Step | Value |
|---|---|
| Length n | 5 |
| Total sum | 21 |
| Sum of array | 18 |
| Missing number | 3 |
Why This Works
Step 1: Calculate expected sum
The formula total = (n+1)*(n+2)//2 gives the sum of all numbers from 1 to n+1, which is what the array should contain if no number was missing.
Step 2: Sum the given array
Adding all elements in the array gives the actual sum of the numbers present.
Step 3: Subtract to find missing
Subtracting the actual sum from the expected total reveals the missing number because it accounts for the gap.
Alternative Approaches
def find_missing_xor(arr): n = len(arr) + 1 xor_all = 0 xor_arr = 0 for i in range(1, n + 1): xor_all ^= i for num in arr: xor_arr ^= num return xor_all ^ xor_arr # Example usage arr = [1, 2, 4, 5, 6] print(find_missing_xor(arr))
def find_missing_sort(arr): arr.sort() for i in range(len(arr)): if arr[i] != i + 1: return i + 1 return len(arr) + 1 # Example usage arr = [1, 2, 4, 5, 6] print(find_missing_sort(arr))
Complexity: O(n) time, O(1) space
Time Complexity
The solution loops through the array once to sum elements, so it runs in linear time O(n).
Space Complexity
Only a few variables are used for sums and length, so space complexity is constant O(1).
Which Approach is Fastest?
The sum formula method is fastest and simplest. XOR is also O(n) but can be faster in some cases. Sorting is slower at O(n log n).
| Approach | Time | Space | Best For |
|---|---|---|---|
| Sum formula | O(n) | O(1) | Simple, efficient for consecutive numbers |
| XOR operation | O(n) | O(1) | Avoids overflow, bitwise operations |
| Sorting and checking | O(n log n) | O(1) | Easy to understand, less efficient |