You are given an array with all the numbers from 1 to N appearing exactly once, except for two number that is missing. How can you find the missing number in O(N) time and 0(1) space?
You can return the missing numbers in any order.
Example 1:
Input: [1]
Output: [2,3]
Example 2:
Input: [2,3]
Output: [1,4]
Note:
nums.length <= 30000
Solutions
Solution 1
Thinking
Two numbers are missing from \(1\ldots n\). Sum and sum-of-squares work but squares overflow easily.
XOR of everything is \(a\oplus b\). lowbit splits them into different groups (that bit is \(1\) in one and \(0\) in the other); XOR inside a group isolates each.
Compute \(xor\), then XOR values with \(diff=xor\&(-xor)\) set to get \(a\), and \(b=xor\oplus a\). Linear time, constant space.