Example 1
ready- Input
nums = [ 3, 0, 1 ]- Expected
2- Why
- the range is 0 through 3, and 2 is absent
A workshop labels n + 1 storage bins from 0 through n, but today's inventory lists
only n of those labels. One label never made it onto the sheet.
Given an integer array nums of length n, return the missing value from the complete
range 0..n.
The inventory has strict ground rules:
nums is distinct.0 and n, inclusive.1 <= nums.length <= 100_0000 <= nums[i] <= nums.lengthnums are distinct.0..nums.length is missing.Hints
If you sort a copy, the first position whose index doesn't equal its value reveals the gap. Remember the case where every visited position matches.
The indices contribute 0 through n - 1, while the array contributes every value
except one. Add n itself, then look for an operation that cancels matching values.
A value XORed with itself becomes zero. XOR n, every index, and every array value;
all present numbers cancel in pairs, so the missing one remains.
The sum formula n * (n + 1) / 2 also gives a linear-time answer. Why might XOR be a
safer choice in a language where integer addition can overflow?
Visible cases
nums = [
3,
0,
1
]2nums = [
0,
1
]2nums = [
9,
6,
4,
2,
3,
5,
7,
0,
1
]8Interview signal
Sort a copy of the values. In the complete sequence, position i should hold i, so
the first mismatch is the missing number. If every stored value matches its position,
the missing value is n itself.
def missing_number(nums: list[int]) -> int:
ordered = sorted(nums)
for expected, value in enumerate(ordered):
if value != expected:
return expected
return len(nums)Time O(n log n). Space O(n) for the sorted copy.
Exclusive OR (XOR) is a bitwise operation whose matching inputs cancel:
value ^ value == 0. You can regroup and reorder XOR operations without changing the
result.
Start the accumulator at n. Then XOR each index and each array value into it. Across
the whole loop, the indices plus that initial n supply every number in 0..n. The
array supplies every one of those numbers except the missing value. Every present value
therefore appears twice and cancels.
def missing_number(nums: list[int]) -> int:
missing = len(nums)
for index, value in enumerate(nums):
missing ^= index ^ value
return missingTime O(n). Space O(1) — no sorting and no set proportional to the input.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
2