Cancel equal values with XOR
Use occurrence promises to find one or two odd-frequency values.
Understand the idea
XOR is associative and commutative, x XOR x = 0, and x XOR 0 = x. XORing every item therefore cancels values appearing an even number of times. It identifies a single odd-frequency value only when the problem promises that there is exactly one.
Trace a small example
For [4, 7, 4, 2, 2], cancellation leaves 7. If exactly two values a and b have odd counts, the total is a XOR b, which is nonzero. Choose one set bit of that total to split the input into two groups; a and b fall into different groups, and equal values cancel within each.
Conditions and cost
One scan takes O(n) time and O(1) additional state; the two-value method uses another scan. The XOR of arbitrary data is not a general duplicate detector and does not prove the promised occurrence pattern.
What does XOR of all values tell you without any occurrence promise?
Turn the idea into code
Find the two odd-frequency values in [3, 5, 3, 8, 5, 12].
Give me a hint
Cancel equal pairs, then split on a set bit of 8 XOR 12.
Show the explained solution
The total XOR is 4. Bit 2 separates 8 from 12, so the two group XORs recover 8 and 12.
Your notes
Mark complete when you can explain it yourself.