XOR tricks
XOR has three handy facts: x ^ x = 0, x ^ 0 = x, and the order does not matter. So XOR-ing a list makes every pair cancel, leaving what appears an odd number of times. With a split by one differing bit, or by counting bits modulo 3, the same idea finds values that appear once among pairs or triples.
How to recognise it
- Every value appears twice (or three times) except one or two, and you need O(1) extra memory.
- The question asks for the XOR of a range or a whole list.
- Two values must be told apart by a bit where they differ.
The idea in one picture
XOR is a light switch per bit: every value presses the switches where it has a 1. Pressing the same switch twice puts it back. After every value has pressed its switches, only the switches pressed an odd number of times are on.
Three versions of "find the single"
| Everyone else appears | Method |
|---|---|
| twice, one single | XOR of everything |
| twice, two singles | XOR everything, split by a bit of the result, XOR each group |
| three times | count each bit modulo 3 (with two masks, ones and twos) |
XOR of a range
The running XOR 1 ^ 2 ^ … ^ n follows a period of 4: it is n, 1, n + 1, 0 for n mod 4 = 0, 1, 2, 3. The XOR
of l..r is xorUpTo(r) ^ xorUpTo(l - 1), because the shared prefix cancels.
Common mistakes
- Using XOR when values appear three times: three copies XOR to the value itself, not 0.
- Computing
n & -non the most negative int in languages where negation overflows; it still works in Java and C++ two's complement, but be careful with unsigned conversions. - Forgetting that XOR-ing a range needs
l - 1, notl, for the prefix.
Problems
- Single Numbereasyguide ready
- Single Number IImediumguide ready
- Single Number IIImediumguide ready
- XOR of numbers in a given rangemediumguide ready