Skip to content
StackDecode
Bit manipulationAnimated

XOR-based Algorithms

a ^ a = 0 and a ^ 0 = a, so pairs cancel out.

Time

O(n)

Extra space

O(1)

Use it for

Finding odd-one-out values; swapping without a temp.

How it works

  1. XOR (^) gives 1 where two bits differ and 0 where they are the same.
  2. Two handy facts: x ^ x = 0 and x ^ 0 = x.
  3. So a ^ b ^ b = a: XOR-ing with the same value twice undoes it.
  4. That lets you swap two numbers without a temporary variable: a ^= b; b ^= a; a ^= b.

Watch it run

Loading animation…