Single Number II – Solution & Complexity
Solution Walkthrough
1. Why plain XOR is not enough
- XOR cancels values that appear an even number of times.
- Here duplicates appear three times (odd), so XOR does not cleanly remove them.
- We need to reason bit by bit instead.
2. Count each bit modulo three
- For each of the 32 bit positions, count how many numbers have that bit set.
- Every tripled value contributes a multiple of three, so
count % 3isolates the unique number's bits. - Rebuild the answer from the remaining bits (sign-extending the top bit for negatives).
3. Constant-space bitmask automaton
- Track two masks:
onesholds bits seen once,twosholds bits seen twice. - A bit resets to zero once it has been seen three times.
- After processing every number,
onesis exactly the unique value.
4. Two-mask solution
ones = (ones ^ num) & ~twosrecords bits appearing a first time while clearing any at two.twos = (twos ^ num) & ~onespromotes bits to the two state, clearing any now back at one.- This is
O(n)time andO(1)space with no per-bit loop.
5. Dry run
Trace nums = [2, 2, 3, 2] (binary 2 = 10, 3 = 11).
| num | ones | twos |
|---|---|---|
| start | 00 | 00 |
| 2 | 10 | 00 |
| 2 | 00 | 10 |
| 3 | 01 | 10 |
| 2 | 01 | 00 |
Final ones = 01 = 3, the unique value.
6. Final solution and complexity
The two-mask automaton returns the unique value in O(n) time and O(1) extra space.