Skip to content
StackDecode
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

  1. XOR everything. Pairs cancel, leaving x ^ y where x and y are the two unique numbers.
  2. 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.
  3. Split all numbers into two groups by whether they have that bit. Each pair stays together; x and y land in different groups.
  4. XOR each group separately to recover x and y.

Watch it run

Loading animation…