Command Palette

Search for a command to run...

← All patterns

Pattern · Bits & Math

Bit Manipulation

Use XOR, AND, OR and shifts to test, set and cancel bits, often in O(1) space.

Time O(n) or O(1) · Space O(1)

Taught in Module 34: Bit Manipulation

Think of it like this

Light switches in a row: XOR flips a switch, and flipping it twice puts it back, so pairs cancel out.

Clues that point here

  • → "Every element appears twice except one"
  • → Count set bits
  • → Power of two
  • → Subsets as bit masks
  • → No extra space allowed

Not this pattern when

  • ✕ A hash map is clearer and space isn't limited

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Bit Manipulation · template
int single = 0;
for (int x : nums) single ^= x;      // pairs cancel: x ^ x = 0
// useful tricks
boolean isPowerOfTwo = n > 0 && (n & (n - 1)) == 0;
int lowestBit = n & -n;
int bits = Integer.bitCount(n);

Common versions

  • Single number
  • Number of 1 bits
  • Counting bits
  • Reverse bits
  • Missing number (XOR)
  • Sum of two integers without +

Practice problems with this pattern