Pattern 18 of 18 · Final Stretch

Bit Manipulation

XOR tricks, bit masks, and shifting — small operations with outsized interview value.

Work directly on a number's binary representation using bitwise operators — often turning an O(n) or O(log n) problem into a handful of O(1) operations.

Key concepts

  • XOR cancels out identical values (x ^ x = 0), which is why it's used to find a single "odd one out" among pairs.
  • AND/OR/shifts are used to check, set, clear, or move individual bits.
  • `n & (n - 1)` clears the lowest set bit — a classic trick for counting set bits.

When to use it

  • The problem talks about bits directly (count set bits, reverse bits, single number among duplicates).
  • You want a constant-time trick instead of a loop for a numeric problem.

Tips

  • XOR-ing every element together is the standard trick when "every value appears twice except one."
  • `n & (n - 1)` removes the lowest set bit — useful for counting bits or checking if a number is a power of two.
  • Watch for language-specific behavior with negative numbers and sign bits when shifting.

Practice problems (7)

Blind 75 (5):

More from Blind 150 (2):

See the full roadmap →