Missing Number – Solution & Complexity
Solution Walkthrough
Step 1: Use the range guarantee
- The numbers must be exactly the values from
0ton, except one missing entry. - That guarantee gives a closed-form expectation we can compare against the actual array.
- The numbers must be exactly the values from
Step 2: Brute-force membership checks
- For every value from
0throughn, scan the array to see whether it exists. - This works, but the nested search costs
O(n^2)time.
- For every value from
Step 3: Compare expected and actual totals
- The full range
0..nsums ton * (n + 1) / 2. - Since exactly one value is missing and nothing is duplicated, subtracting the actual array sum reveals that missing value immediately.
- The full range
Step 4: Compute the missing value in one pass
- First compute the expected range sum.
- Then subtract every number in the array and return the remainder.
Step 5: Dry run / arithmetic trace
Trace
nums = [3, 0, 1].quantity value n3expected sum 0 + 1 + 2 + 36actual array sum 3 + 0 + 14missing number expected - actual2Because the array contains distinct numbers, no extra bookkeeping is needed beyond the running total.
Step 6: Final solution and complexity
The sum formula finds the missing value in
O(n)time andO(1)extra space.