Problem overview
The method missingNumber receives a list nums of n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one of them is absent from nums. The method returns it.
For nums = [3, 0, 1] we have n = 3, so the numbers 0, 1, 2 and 3 should all appear. Only 2 is absent, so the result is 2. The missing number can be n itself: for [0, 1] the result is 2. It can also be 0: for [1] the result is 0.
The lesson asks for O(n) time and O(1) extra space.
Approach: let every present number cancel itself out
Two simple ideas come first. You could sort the list and look for the first gap, which costs O(n log n). Or you could put the numbers in a set and test each value from 0 to n, which is O(n) time but O(n) space. XOR gets both bounds down.
XOR (^ in Python) has three properties that matter here:
x ^ x = 0: a number cancels with itself;x ^ 0 = x: zero changes nothing;- the order doesn't matter.
Now build a collection in which every number from 0 to n appears once, from the indices of the list plus n. The indices of nums run from 0 to n - 1, so adding n completes the range. Put that collection together with the values of nums. Each value that is present appears twice, once as an index (or n) and once as a value, and cancels. The missing number appears only among the indices, so it is the only one left.
Step by step
- Start from
n. Createresultand set it tolen(nums). The indices stop atn - 1, sonhas to go in here, at the start. - Visit every index. A
forloop withioverrange(len(nums))covers the indices 0 ton - 1. - XOR in both the index and the value. The statement
result ^= i ^ nums[i]combinesiandnums[i]intoresult. - Return
result. Every number that is innumswent in twice and cancelled. What is left is the missing one.
The solution in Python
class Solution:
def missingNumber(self, nums: List[int]) -> int:
result = len(nums)
for i in range(len(nums)):
result ^= i ^ nums[i]
return result
Python details worth knowing
^=is XOR-assign.result ^= xmeansresult = result ^ x. Because XOR is associative,result ^= i ^ nums[i]gives the same result as writing two separate^=lines.^is not a power operator. Exponentiation is**in Python.^is bitwise XOR.- No overflow worries. Python integers can be any size, and XOR of numbers up to
nnever exceeds the largest of them in bit length.
Trace on [3, 0, 1]
Here result starts at 3. The table shows its value after each turn of the loop:
i | nums[i] | result afterwards |
|---|---|---|
| 0 | 3 | 0 |
| 1 | 0 | 1 |
| 2 | 1 | 2 |
The method returns 2. In this run the 3 from the list cancelled the starting 3, the 0 cancelled index 0, the 1 cancelled index 1, and index 2, which has no partner among the values, remained.
Complexity
Time: the loop visits each index once and does two XORs per index, so the time is O(n).
Space: a single number, result, is kept, so the extra space is O(1).
Edge cases and common mistakes
- The missing number is
n. For[0, 1]the starting value 2 never meets a partner among the values, so the method returns2. - The missing number is 0. For
[1]the loop XORs 0 and 1 intoresult = 1, which leaves1 ^ 0 ^ 1 = 0. The method returns0. - Starting
resultat 0. That leavesnout of the collection of indices, so the answer is wrong whenever the missing number is notn: it ends up XORed withn. - Looping with
range(len(nums) + 1). That readsnums[n], one past the end, and raises anIndexError. - Relying on the formula
n * (n + 1) // 2minus the sum. This also works in Python, because integers don't overflow, but in languages with fixed-size integers the sum can overflow, and the XOR version doesn't have that problem.
Testing
These results come from running the solution:
nums | Result |
|---|---|
[3, 0, 1] | 2 |
[0, 1] | 2 |
[1] | 0 |
