Problem overview
The method missingNumber receives nums, an array of n distinct numbers, each between 0 and n. The range from 0 to n holds n + 1 numbers, so exactly one of them is absent. The method returns it.
For nums = [3, 0, 1], n is 3, so the numbers should be 0, 1, 2 and 3. Only 2 is absent, so the result is 2. The missing number can also be n itself, as in [0, 1] (result 2), or 0, as in [1] (result 0).
The note asks for O(n) time and O(1) extra space.
Approach: give every present number a partner
There are simpler ways. Sorting the array and scanning for the first gap costs O(n log n). A Set of the values, checked against 0 to n, is O(n) time but O(n) space. Adding up 0 to n and subtracting the array's sum also works in constant space, and this lesson uses XOR instead.
XOR has three properties that matter here: x ^ x is 0, x ^ 0 is x, and the order of the operands doesn't matter. So when a collection of numbers is XORed together, any number that appears twice cancels out, and what remains is the XOR of the numbers that appear once.
No number repeats in nums, so we create the repeats. The indices of the array run from 0 to n - 1, and adding n gives every number from 0 to n exactly once. If we XOR those numbers together with every value in nums, each value that is present meets its equal among the indices and cancels. The missing number appears among the indices (or as n) but not among the values, so it is the only one left.
Here is a run on [3, 0, 1], starting with result = 3 (that is, n):
i nums[i] result after i ^ nums[i] is XORed in
0 3 0
1 0 1
2 1 2
The result is 2, the missing number.
Step by step
- Start
resultatnums.length, which isn. The indices stop atn - 1, sonhas to enter the XOR here. - Loop over every index from 0 to
nums.length - 1. - XOR in the index and the value:
result ^= i ^ nums[i]. The index supplies each number from 0 ton - 1, and the value cancels the one it equals. - Return
result. Every number innumswent in twice and cancelled, so what is left is the missing one.
The solution in TypeScript
class Solution {
missingNumber(nums: number[]): number {
let result = nums.length;
for (let i = 0; i < nums.length; i++) {
result ^= i ^ nums[i];
}
return result;
}
}
Some TypeScript details:
^=is compound assignment.result ^= xmeansresult = result ^ x. The right side,i ^ nums[i], is evaluated first, but since XOR is associative the grouping doesn't change the answer.^is XOR, not a power. Exponentiation in TypeScript is**.- 32-bit integers. Bitwise operators convert their operands to 32-bit integers. With
nup to 100,000 that is no limit. - Types are erased.
number[]checks nothing at run time. If the array held strings,^would still convert them to numbers, so the types are what protects you here.
Complexity
Time: O(n). The loop visits each index once and does two XORs per visit.
Space: O(1). The method keeps one number, result, and the loop variable.
Edge cases and common mistakes
- The missing number is
n. For[0, 1]the indices are 0 and 1, the values are 0 and 1, and everything cancels except the startingn = 2. The result is2. - The missing number is 0. For
[1]the method returns0: the starting 1 cancels with the value 1, and index 0 is left. - Starting at 0 instead of
nums.length. Thennis never XORed in, and the answer is wrong whenever the missing number is notn. For[0]the correct answer is 1, but starting from 0 the method would return 0. - Looping to
nums.lengthinclusive. That would readnums[n], which isundefined, andi ^ undefinedtreats it as 0, which silently changes the result. - Assuming a sorted input. Nothing in the method depends on order:
[9, 6, 4, 2, 3, 5, 7, 0, 1]returns8.
Testing
nums = [3, 0, 1]gives2.nums = [0, 1]gives2.nums = [1]gives0.nums = [0]gives1.nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]gives8.
