Bit manipulation: XOR tricks and the operators you need
The few bitwise operators interviews use, the XOR identities, and the classic problems: single number, counting set bits, power of two.
In short
Numbers are bits, and &, |, ^, <<, >> work on them directly in O(1). Two identities solve many problems: a ^ a = 0 and a ^ 0 = a. The classic: XOR everything and the pairs cancel, leaving the single one.
The operators
| Operator | Does | Example (5 = 101, 3 = 011) |
|---|---|---|
| a & b | 1 where both have 1 | 5 & 3 = 001 = 1 |
| a | b | 1 where either has 1 | 5 | 3 = 111 = 7 |
| a ^ b | 1 where bits differ | 5 ^ 3 = 110 = 6 |
| a << k | Shift left: multiply by 2ᵏ | 5 << 1 = 1010 = 10 |
| a >> k | Shift right: divide by 2ᵏ (floor) | 5 >> 1 = 10 = 2 |
XOR: pairs cancel out
XOR is commutative and a ^ a = 0. So if every number appears twice except one, XORing the whole array leaves exactly that one: no hash map, O(1) space.
x (binary)
1def single_number(nums):2 x = 03 for n in nums:4 x ^= n5 return x
Variables
Tricks worth memorising
| Goal | Expression | Why it works |
|---|---|---|
| Is bit i set? | (x >> i) & 1 | Move bit i to the end and mask the rest |
| Set / clear bit i | x | (1 << i) / x & ~(1 << i) | Mask with a single 1 |
| Is x a power of two? | x > 0 and x & (x - 1) == 0 | A power of two has exactly one 1 bit |
| Remove the lowest set bit | x & (x - 1) | Subtracting 1 flips the lowest 1 and the zeros below it |
| Count set bits | while x: x &= x - 1; c += 1 | One iteration per 1 bit |
Key takeaways
- 01& | ^ << >> are O(1) and let you treat a number as a set of flags.
- 02a ^ a = 0 and a ^ 0 = a: duplicates cancel, so XOR finds the odd one out in O(1) space.
- 03x & (x - 1) removes the lowest set bit: use it to count bits or test a power of two.
- 04Check integer width and sign rules in your language.
Check your understanding
1 of 3
What is 6 ^ 6?
Related topics
Hash maps
A hash map stores key → value pairs and finds any key in O(1) on average. Whenever a loop keeps asking "have I seen this before?", a hash map usually turns O(n²) into O(n).
8 min read →Primes, GCD & fast power
Check one number for primality by trying divisors up to √n. Find all primes up to n with the sieve in O(n log log n). gcd(a, b) = gcd(b, a mod b). And x^n takes only O(log n) multiplications by squaring.
8 min read →