Single Number III
Difficulty: Medium · Pattern: Bit Manipulation · LeetCode #260
Exactly two elements appear once, and all others appear exactly twice. Return the two singles, in any order. Use O(n) time and O(1) space.
Examples
text
[1,2,1,3,2,5] → [3,5]
[-1,0] → [-1,0]Hints
- XOR of everything gives
a ^ b, which is non-zero because a ≠ b. - Any set bit of
a ^ bis a bit where a and b differ. Use it to split all numbers into two groups.
Approach
x = XOR of all=a ^ b.low = x & -xisolates the lowest set bit. a and b differ there.- Split the numbers on whether
num & lowis set. Each pair lands in the same group and cancels, so XORing each group yields a and b.
Watch for INT_MIN overflow on -x in fixed-width languages. In JS, x & -x works on signed 32-bit values, and in Python it's exact.
Complexity
Time: O(n). Space: O(1).
Python solution
def singleNumber(nums):
x = 0
for n in nums:
x ^= n
low = x & -x
a = 0
for n in nums:
if n & low:
a ^= n
return [a, x ^ a]JavaScript solution
function singleNumber(nums) {
let x = 0;
for (const n of nums) x ^= n;
const low = x & -x;
let a = 0;
for (const n of nums) if (n & low) a ^= n;
return [a, x ^ a];
}