Missing Number
A list nums holds n distinct integers, all taken from the range 0 to n inclusive. That range contains n + 1 values, so exactly one of them is absent from the list.
Return the absent value. The list is in no particular order.
Can you do it in linear time with only constant extra memory?
Example 1
Example 2
Example 3
Constraints
1 <= n == nums.length <= 1040 <= nums[i] <= n- All values in
numsare distinct.
Pattern Path · Math, Bits & Strings · problem 33 of 169
n · (n + 1) / 2.Start simple
For each candidate 0..n, scan the list to see whether it is present: O(n²) time; sorting first or using a set brings it to O(n log n) or O(n) time with extra space.
The key idea
The range 0..n is fully known in advance, so compare what the list should add up to with what it does add up to.
The expected total of 0 + 1 + ... + n is n · (n + 1) / 2 (Gauss's formula). Every value except one contributes to both totals, so all of them cancel when you subtract the actual sum, and only the missing value survives.
An equivalent trick uses XOR: XOR together every index 0..n and every element. Each present value appears twice (once as an index, once as an element) and cancels to 0, leaving the missing one. The XOR version is handy in languages with fixed-width integers because it can never overflow, while the sum version is easier to read.
Both run in a single pass and keep just one running number.
Complexity
- Time:
O(n) - Space:
O(1)
Python
class Solution:
def missingNumber(self, nums):
n = len(nums)
expected = n * (n + 1) // 2 # sum of 0..n
return expected - sum(nums)
JavaScript
var missingNumber = function(nums) {
const n = nums.length;
let missing = n * (n + 1) / 2; // sum of 0..n
for (const x of nums) missing -= x;
return missing;
};
What the interviewer is checking
It tests whether you exploit the structure of the input (a known, contiguous range) instead of reaching for a set or a sort, and whether you think about integer overflow.
Mistakes to avoid
- Forgetting that the missing value can be 0 or n itself.
- Summing the range only up to
n - 1(an off-by-one on the upper bound). - Integer overflow of the sum in fixed-width languages; XOR avoids it.
Follow-ups to expect
- What if two values are missing? (Use sum and sum of squares.)
- What if the list is sorted? (Binary search where nums[i] != i.)
- What if values can repeat? (Index marking or cyclic sort.)
In real software
Detecting a lost packet in a numbered sequence or a skipped invoice number is often done with a running checksum like this rather than storing every ID.