Pairs cancel out
Find the one value without a partner by XOR-ing everything together. About 8 minutes.
XOR compares bit by bit
XOR is a spot-the-difference game: the result has a 1 wherever the two inputs differ. A number compared with itself shows no difference, so it gives 0. Compared with 0 nothing changes, so you get the number back.
Order does not matter either, so 5 XOR 9 XOR 5 is just 9: the two 5s cancel.
5 ^ 5 # 0 5 ^ 0 # 5 5 ^ 9 ^ 5 # 9
- acc
- 4 (100)
acc = 0 ^ 4 = 4 (100 in binary).
Let the pairs cancel
Imagine a room where everyone arrived in pairs except one person who came alone. If every pair shakes hands and leaves, the loner is left standing. XOR does that to numbers.
XOR the whole list together: each value that appears twice meets its partner and vanishes, and the one without a partner remains. No sets, no sorting, no extra memory.
result = 0
for x in nums:
result ^= x
return resultWhat is 4 ^ 1 ^ 2 ^ 1 ^ 2?
- A4
- B10
- C0
Show the answer
4. The 1s cancel and the 2s cancel, leaving 4.
The number without a partner
Every value in a non-empty list appears exactly twice, except one that appears once. Return that one.
nums = [4, 1, 2, 1, 2] → 4
1 ≤ n ≤ 1,000,000 (n odd) · values may be negative · use O(1) extra memory