Missing Number
Given an array nums containing n distinct numbers in the range [0, n], return the one number in that range that is missing from nums. XOR every index together with every value , plus n itself. Every number that is actually present cancels its own index, leaving only the missing number.
Constraints
- n == nums.length
- 1 ≤ n ≤ 104
- 0 ≤ numsi ≤ n
- All values are distinct
Example
nums = [3, 0, 1]2Explanation n = 3, and the range [0, 3] is missing the number 2.
In plain terms
- XOR
- XOR-ing a value with itself gives 0. If every index from 0 to n and every value in nums is XORed together, every present number cancels against its own index — only the missing one has nothing to cancel it.
XOR every index and value into one running result
result = n = 3. XOR with index 0 and nums[0]=3: 3 ^ 0 ^ 3 = 0.
What happens in this step
result = n = 3
i ^ nums[i] = 0 ^ 3
0 = 00000000
3 = 00000011
--------
00000011 = 3
result ^= 3
3 = 00000011
3 = 00000011
--------
00000000 = 0
Index 0 and its value 3 combine to 3, then merge into result. Result also started at 3, so the two 3s cancel — result becomes 0.Steps to visualize
- Start a running result at n (the length of nums).
- For each index i, XOR the result with i and with numsi.
- Every number that appears in nums cancels out against its matching index.
- What remains after the last index is the missing number.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
result = n = 3. XOR with index 0 and nums[0]=3: 3 ^ 0 ^ 3 = 0.
What happens in this step
result = n = 3
i ^ nums[i] = 0 ^ 3
0 = 00000000
3 = 00000011
--------
00000011 = 3
result ^= 3
3 = 00000011
3 = 00000011
--------
00000000 = 0
Index 0 and its value 3 combine to 3, then merge into result. Result also started at 3, so the two 3s cancel — result becomes 0.Solution
function missingNumber(nums) {
let result = nums.length;
for (let i = 0; i < nums.length; i++) {
result ^= i ^ nums[i];
}
return result;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [3, 0, 1] | 2 | example from the docstring |
nums = [0, 1] | 2 | the missing number is the largest value in the range |
nums = [1, 2, 3] | 0 | the missing number is 0 |
nums = [1] | 0 | smallest valid input, single element |
nums = [0] | 1 | smallest valid input, missing the only other value |
nums = [9, 6, 4, 2, 3, 5, 7, 0, 1] | 8 | the missing number sits in the middle of the range |