Learn / Bit manipulation

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 appearsMethod
twice, one singleXOR of everything
twice, two singlesXOR everything, split by a bit of the result, XOR each group
three timescount 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 & -n on 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, not l, for the prefix.

Problems

0 of 4 solved

Check yourself

What is 5 ^ 3 ^ 5?

The XOR of the whole list is a ^ b, where a and b are the two singles. Why is a bit set in a ^ b useful?

What is 1 ^ 2 ^ … ^ n when n mod 4 is 3?