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
- XOR (^) gives 1 where two bits differ and 0 where they are the same.
- Two handy facts: x ^ x = 0 and x ^ 0 = x.
- So a ^ b ^ b = a: XOR-ing with the same value twice undoes it.
- That lets you swap two numbers without a temporary variable: a ^= b; b ^= a; a ^= b.
Watch it run
Loading animation…