Problem overview
The method missingNumber(int[] nums) receives n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one of them is absent, and the method returns it.
For nums = [3, 0, 1] we have n = 3, so the numbers should be 0, 1, 2 and 3. The array holds 0, 1 and 3, so the answer is 2. For [0, 1] the missing number can be n itself, 2. For [1] it can be 0.
The target is O(n) time and O(1) extra space.
Approach: let equal numbers cancel
Two easy ways exist. A boolean array or a hash set records which numbers were seen, but it uses O(n) extra space. Adding up 0 + 1 + ... + n with the formula n * (n + 1) / 2 and subtracting the array's sum works in O(1) space, though it needs care with overflow for large n. This lesson uses XOR.
XOR has three properties that matter here: x ^ x = 0, x ^ 0 = x, and the order of operands doesn't matter. So when a value appears twice in a chain of XORs, the two copies cancel, whatever else is in the chain.
Now build a chain in which every number from 0 to n appears once from a known source, and every value of nums appears once more. The indices of nums run from 0 to n - 1, and adding n gives every number from 0 to n exactly once. Then XOR in every value of nums. Each value that is present meets its equal and cancels. The missing number has no partner among the values, so it is the only one left.
For nums = [3, 0, 1], result starts at 3, and each pass of the loop changes it like this:
start 3
i=0 nums[i]=3 result=0
i=1 nums[i]=0 result=1
i=2 nums[i]=1 result=2
The method returns 2, which is the missing number.
Step by step
- Create
resultas anintand start it atnums.length, which isn. The indices stop atn - 1, sonhas to be put in here. - Visit every index with a
forloop from 0 whilei < nums.length. - XOR both the index and the value into
resultwith^=. The index supplies the numbers 0 ton - 1and the value cancels its equal. - Return
resultafter the loop.
The solution in Java
class Solution {
public int missingNumber(int[] nums) {
int result = nums.length;
for (int i = 0; i < nums.length; i++) {
result ^= i ^ nums[i];
}
return result;
}
}
The Java details worth a closer look:
^is XOR, not a power. In Java^on integers is bitwise exclusive OR. There is no power operator;Math.powdoes that.^=evaluates the right side first.result ^= i ^ nums[i]meansresult = result ^ (i ^ nums[i]). Since XOR is associative, it makes no difference whether the index and the value are combined first.- No overflow. XOR never carries, so the result always fits in an
int. The sum-based method can overflow for largen, and this one cannot. nums.lengthis a field. For arrays it has no parentheses, unlikesize()on a list.
Complexity
Time: O(n). The loop visits each index once and does two XORs per index.
Space: O(1). The method keeps one number, result, plus the loop counter.
Edge cases and common mistakes
- The missing number is
n. For[0, 1],resultstarts at 2, every other number cancels, and the method returns 2. Ifresultstarted at 0 instead,nwould never be included and this case would fail. - The missing number is 0. For
[1]the method returns 0. XOR with 0 changes nothing, and the result is still correct. - Looping to
ninstead ofn - 1.nums[n]doesn't exist and throws anArrayIndexOutOfBoundsException. The array has indices 0 ton - 1. - Using
+or-by mistake. Only XOR makes equal numbers cancel by themselves. Mixing operators gives wrong answers. - Relying on sorted input. The array can be in any order. Because XOR is order-independent, nothing needs sorting.
Testing
nums = [3, 0, 1]gives 2.nums = [0, 1]gives 2.nums = [1]gives 0.nums = [9, 6, 4, 2, 3, 5, 7, 0, 1]gives 8.
