Algorithms Playbook
ConceptTime O(n) or O(bits) · Space O(1)8 min read

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

OperatorDoesExample (5 = 101, 3 = 011)
a & b1 where both have 15 & 3 = 001 = 1
a | b1 where either has 15 | 3 = 111 = 7
a ^ b1 where bits differ5 ^ 3 = 110 = 6
a << kShift left: multiply by 2ᵏ5 << 1 = 1010 = 10
a >> kShift 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.

XOR: pairs cancel, the single one survives
Speed
0411223142everything appears twice except one

x (binary)

00102030
1def single_number(nums):
2 x = 0
3 for n in nums:
4 x ^= n
5 return x
x starts at 0. XOR rules: a ^ a = 0 and a ^ 0 = a, and order doesn't matter. So every number that appears twice will cancel itself.

Variables

x0
Step 1/7· Steps: 0
Use an odd count of numbers where all but one appear twice (the default has 5). If the input isn't like that, the result is just the XOR of everything.

Tricks worth memorising

GoalExpressionWhy it works
Is bit i set?(x >> i) & 1Move bit i to the end and mask the rest
Set / clear bit ix | (1 << i) / x & ~(1 << i)Mask with a single 1
Is x a power of two?x > 0 and x & (x - 1) == 0A power of two has exactly one 1 bit
Remove the lowest set bitx & (x - 1)Subtracting 1 flips the lowest 1 and the zeros below it
Count set bitswhile x: x &= x - 1; c += 1One 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