Example 1
- Input
- nums = [3, 0, 1]
- Output
- 2
With n = 3 the full range is 0 to 3, and 2 is the only value absent.
Find the one number missing from an array that holds n distinct values from the range 0 to n, in linear time with constant extra space.
Given an array nums holding n distinct numbers drawn from the range 0 to n, return the single number in that range that does not appear.
Sorting exposes the gap but costs more than linear time, and a lookup set costs linear space. The follow-up asks for both at once: linear time with only constant extra space.
n == nums.lengthnums are unique.With n = 3 the full range is 0 to 3, and 2 is the only value absent.
With n = 2 the full range is 0 to 2, and 2 is the only value absent.
With n = 9 the full range is 0 to 9, and 8 is the only value absent.
The one-element input must come from [0, 1]. Since 1 is present, the missing value is zero, which must not be confused with a failure sentinel.
There are n + 1 possible values but only n distinct array entries, so exactly one value is absent. For [3, 0, 1], compare the full range [0, 1, 2, 3] with the input: only 2 has no partner. A set makes this comparison explicit. XOR compresses it into one accumulator because equal values cancel, regardless of their order in the array.
Reveal Lookup Set: intuition, complexity, and code
0 to n in some order. What single value breaks that picture in [3, 0, 1]?n: pairs cancel and only the missing number survives.n itself, as in [0, 1]: no index reaches it, but the seed n = 2 survives the folding.[1]: one fold still isolates the missing 0.0 instead of n, which drops the top of the range and answers 0 whenever n itself is missing.When a complete range has exactly one hole, pairing each element against its expected partner with XOR exposes the hole with no storage.