Problem overview
The method MissingNumber receives an int[] nums of n distinct numbers, each between 0 and n. The range 0 to n holds n + 1 numbers, so exactly one is absent. The method returns it.
For [3, 0, 1], n is 3, the full range is 0, 1, 2, 3, and the missing number is 2. For [0, 1] it is 2, which is n itself. For [1] it is 0.
Approach: let the pairs cancel
Sorting the array and looking for the gap works, but it costs O(n log n). A hash set gives O(n) time but needs O(n) extra space. The lesson asks for O(n) time and O(1) space, and XOR does that.
XOR (^) has three properties that matter here: x ^ x = 0, x ^ 0 = x, and the order of operands doesn't matter. So if every number appears an even number of times in a long XOR chain, everything cancels, and a number that appears an odd number of times is what remains.
Build a chain in which every number from 0 to n appears once from the "expected" side, and every value in nums appears once from the "actual" side. The expected side is the indices 0 to n - 1 plus n itself. A value present in nums appears on both sides and cancels. The missing number appears only on the expected side, so it is what is left.
Step by step
- Start
resultatnums.Length, which isn. The indices stop atn - 1, sonhas to be added at the start. - Loop
ifrom 0 whilei < nums.Length. The indices 0 ton - 1, together with thenalready inresult, are every number from 0 tononce. - XOR both
iandnums[i]intoresultwith^=. - Return
result.
Tracing [3, 0, 1], result starts at 3 and after each index is:
i=0 result=0
i=1 result=1
i=2 result=2
The last value, 2, is the missing number. At i = 0, for instance, the 3 in result met the 3 in nums[0] and cancelled.
The solution in C#
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;
}
}
Details worth knowing:
Lengthis a property of arrays, written without parentheses. AList<int>usesCountinstead.result ^= i ^ nums[i]meansresult = result ^ (i ^ nums[i]). The right side is evaluated first, and because XOR is associative the grouping doesn't change the answer.- No overflow risk. XOR never carries, so unlike a running sum it can't overflow an
int.
Complexity
Time: O(n). One pass, two XORs per index. Space: O(1). A single int besides the loop variable.
Edge cases and common mistakes
- The missing number is
n. For[0, 1]the method returns 2. That is whyresultstarts atnums.Lengthand not at 0: starting at 0 would leavenout of the chain. - The missing number is 0. For
[1]it returns 0. The XOR of 0 with anything leaves that thing unchanged, so 0 needs no special case. - A longer example. For
[9,6,4,2,3,5,7,0,1],nis 9 and the method returns 8. - Summing instead. The formula
n * (n + 1) / 2minus the sum ofnumsalso finds the answer, but forn = 100000the total is about 5 billion, which doesn't fit in anint, so the sums needlong. XOR avoids the question. - Duplicates. The method relies on the numbers being distinct. A repeated value would cancel itself and leave a wrong result.
Testing
[3, 0, 1]gives2.[0, 1]gives2.[1]gives0.[9, 6, 4, 2, 3, 5, 7, 0, 1]gives8.
