Bit manipulationAnimated
Find Two Non-Repeating Elements
XOR all, split the numbers by a differing bit, and XOR each group.
Time
O(n)
Extra space
O(1)
Use it for
Two unique values among pairs.
How it works
- XOR everything. Pairs cancel, leaving x ^ y where x and y are the two unique numbers.
- x and y differ, so x ^ y has at least one set bit. Pick the lowest set bit: x and y differ at that position.
- Split all numbers into two groups by whether they have that bit. Each pair stays together; x and y land in different groups.
- XOR each group separately to recover x and y.
Watch it run
Loading animation…