Single Number II – Solution & Complexity
Solution Walkthrough
Step 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.
Step 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).
Step 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.
- Track two masks:
Step 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.
Step 5: Dry run
Trace
nums = [2, 2, 3, 2](binary2 = 10,3 = 11).num ones twos start 00002 10002 00103 01102 0100Final
ones = 01 = 3, the unique value.Step 6: Final solution and complexity
The two-mask automaton returns the unique value in
O(n)time andO(1)extra space.