Missing Number
Find the number from 0 to n that an array leaves out, by letting XOR cancel every number that appears twice.
Given an array numsnn
Example 1
Output: 2
Explanation: n = 3, so the range is 0 to 3, and 2 is missing.
Example 2
Output: 2
Explanation: The missing number can be n itself.
Example 3
Output: 8
The Idea
Picture four seats numbered 0 to 3 and three guests, each with a ticket for a different seat. One seat stays empty. In Example 1 the tickets are 3, 0 and 1, so seat 2 is the empty one. Sorting the tickets would show the gap but costs extra time, and ticking seats off on a list costs extra memory.
Here is another way to see it. The array has three slots, with indexes 0, 1 and 2, and n is 3. Together, the indexes and n list every number from 0 to 3 exactly once. The values list every number from 0 to 3 except the missing one. So each present number shows up twice, and the missing number shows up once. How can the pairs cancel each other without matching them up one by one?
Java has an operator for that cancelling: ^int3 ^ 3
Bit positions are counted from the right: position 0 is worth 1, position 1 is worth 2, and position 2 is worth 4. So 3 is 011 in binary, and 2 is 010. A Java int
Look at the picture below. Each row is one of the seven numbers that go into the XOR for [3, 0, 1]
Value 3 pairs with n, value 0 with index 0, and value 1 with index 1. Only the orange row, index 2, labelled no partner, has no twin. In the column for position 0, four rows have a 1, an even count, so the XOR has 0 there. Position 1 has three 1s, an odd count, so the XOR has 1 there.
Why does the count decide it? Two equal numbers put the same bit into every column, so they always add an even number of 1s. Only index 2 adds 1s that nothing matches. That is why the row labelled XOR of all seven reads 010, which is 2: the XOR of everything is exactly the missing number.
Solution Approach
Turning the cancelling into code means seeing why simpler ways fall short, settling which numbers go into the XOR and what the running result starts as, and weighing an optional sum-based way.
Simpler ways and their cost
Why not check each number from 0 to n in turn? Each check scans the whole array, so the work grows with n times n. Sorting the array first and looking for the first index whose value differs takes O(n log n) time. Putting the values in a HashSet
Which numbers go into the XOR
Does each index have to meet its own value? No, because the order of the XORs does not matter. The code walks the array with one loop, and at index iinums[i]
The starting value
Where does n go in? The loop only sees the indexes 0 to n - 1, so n has no index of its own. Starting the running result xx[3, 0, 1][0, 1]
The sum of 0 to n, an alternative
The numbers 0 to n add up to n × (n + 1) / 2, so subtracting the array's sum also leaves the missing number. In Example 1 that is 6 minus 4, which is 2. The catch is size: the product n × (n + 1) is worked out before the division.
In an intlong
Java Solution
The method missingNumber
- First, set the running result
tox , which is n, so n goes into the XOR before the loop.nums.length - Then a
loop moves the indexfor from 0 to n - 1. At each step,i mixes in the index and the value stored there.x ^= i ^ nums[i] - When the loop ends, every present number has met its twin and cancelled, so
holds the missing number, and the method returns it.x
A second method, missingBySumInIntintmain[0][1]
public class MissingNumber {
public static int missingNumber(int[] nums) {
int x = nums.length; // n has no index of its own, so it goes in first
for (int i = 0; i < nums.length; i++) {
x ^= i ^ nums[i]; // a value that is present cancels its matching index
}
return x;
}
// The sum way, computed in int: n * (n + 1) overflows once n passes 46,340.
static int missingBySumInInt(int[] nums) {
int n = nums.length;
int expected = n * (n + 1) / 2;
int sum = 0;
for (int v : nums) {
sum += v;
}
return expected - sum;
}
public static void main(String[] args) {
System.out.println(missingNumber(new int[] {3, 0, 1}));
System.out.println(missingNumber(new int[] {0, 1}));
System.out.println(missingNumber(new int[] {9, 6, 4, 2, 3, 5, 7, 0, 1}));
System.out.println(missingNumber(new int[] {0}));
System.out.println(missingNumber(new int[] {1}));
int[] big = new int[50000]; // 50,000 down to 0, without 12,345
for (int v = 50000, k = 0; v >= 0; v--) {
if (v != 12345) {
big[k++] = v;
}
}
System.out.println("xor: " + missingNumber(big) + ", int sum: " + missingBySumInInt(big));
}
}
Running it prints:
2
2
8
1
0
xor: 12345, int sum: -2147471303
The second line, 2, is Example 2's answer and also n itself. In [0, 1]x[0][1]
Look at the last line. XOR finds 12345 in the large array, while the intint
Complexity
The method reads each slot of the array once and keeps a single running number.
- Time: O(n), because the loop runs once for each of the n slots and does two XORs at each step.
- Space: O(1), because only
and the indexx are kept, and the input array is read without being changed.i
The same cancelling of equal pairs finds the one number without a twin in