mediumBit ManipulationArrays & Hashing

Single Number III

mediumTime: O(n)Space: O(1)

Signals to notice

every element appears twice except twofind both unique elementsXOR then split

Brute force first

Hash map counting. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

XOR all elements — duplicates cancel, leaving a XOR b. Find any set bit in this XOR (it's a bit where a and b differ). Partition all numbers into two groups by this bit. XOR each group separately to get a and b. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

The XOR of all elements equals a XOR b (since all others cancel). Any set bit in this result differentiates a and b — partitioning by that bit separates them into different groups while keeping each group's duplicates paired. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Not understanding why the partition works — within each group, duplicates still cancel via XOR. The differentiating bit ensures a and b land in different groups. The fix is usually to return to the meaning of each move, not just the steps themselves.

Arrays & Hashing Pattern