You are given an array nums of n different numbers. Each one is between 0 and n inclusive. That range holds n + 1 numbers, so exactly one of them is not in the array.
Return the number from 0 to n that is missing.
Example 1
Input: nums = [4, 0, 1, 3] Output: 2 Why: n = 4, and 2 is the only number from 0 to 4 not listed
2 more examples and the constraints
Example 2
Input: nums = [1, 2] Output: 0 Why: the missing number can be 0
Example 3
Input: nums = [0, 1, 2] Output: 3 Why: 0, 1 and 2 are all there, so n itself is missing
Constraints
- 1 ≤ n ≤ 10,000, where n is the length of nums
- 0 ≤ each number ≤ n
- All numbers in nums are different
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort and scanO(n log n)
- Sum formulaO(n)
- XOR cancelO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 numbers | Verdict |
|---|---|---|---|
| Sort and scan | O(n log n) | Passes; does more than needed | |
| Sum formula | O(n) | Passes; one pass, one number | |
| XOR cancel | O(n) | Best; one pass, cannot overflow |
n = length of nums.
Edge cases to test
- Zero is missing. [1, 2] gives 0. Code that starts counting from 1 misses this.
- n is missing. [0, 1, 2] gives 3: every index matches, so the answer is the length.
- A single number. [0] gives 1 and [1] gives 0.
- Unsorted input. The numbers come in any order; none of the O(n) methods care.
Common mistakes
- Forgetting n itself: looping over indices 0 to n − 1 only, so the sum or XOR never includes n.
- Returning n − 1 or the last index when nothing is out of place after sorting, instead of n.
- Using a boolean array of size n instead of n + 1, so marking the value n goes out of bounds.
How to talk through it
- 1Clarify. Is the range always 0 to n with exactly one missing? Are all values different?
- 2Give the simple answer. Sort and find the first index that does not hold its own value; say it is O(n log n).
- 3Use what you know about the range. The full range is known, so compare against it: its sum is n(n + 1) / 2.
- 4Offer XOR. Present numbers cancel as index and value; it is O(1) space and cannot overflow.
- 5Test out loud. Run the cases where 0 is missing and where n is missing.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?