Skip to content
ΣDSA Patterns
Menu
Language

Pattern #25

Bit Manipulation

Recommended

XOR, masks, shifts, and set-bit tricks for O(1) state.

When to use

Pairs cancel, subsets as bitmasks, power-of-two tests, or compact state in DP.

Recognition cues

  • Single number (XOR)
  • Counting bits / power of two
  • Subset DP on masks

Common pitfalls

  • Sign bit / arithmetic vs logical shift confusion
  • Assuming unlimited int width in languages with fixed ints
  • Off-by-one when iterating bits 0..n-1

90-second recognition drill

Which pattern fits best?

  • Single number (XOR)
  • Counting bits / power of two
  • Subset DP on masks

Interactive

Mental model

A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.

Step 1 of 8
4
1
2
1
2

x = 0

Single number via XOR: pairs cancel to 0.

How to think about it

XOR is its own inverse: pairs vanish. n & (n-1) drops the lowest set bit. n & -n isolates it. Bitmasks encode subsets of a small universe (n ≤ 20) for DP or enumeration.

Template shapes

Shape Core move Notes
XOR fold x ^= a[i] Single number
Lowest bit n & -n / n & (n-1) Count / remove
Mask DP for mask in 0..1<<n Subsets

Complexity baseline

Often O(n) word ops, or O(2^n · n) for subset DP.

From template to problem

  1. Map the problem to a bitwise identity.
  2. Watch language-specific int size.
  3. Prefer bit tricks over O(n) scans when the identity is clear.
  4. For masks: iterate submasks carefully if needed.

Template

Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.

Bit Manipulation · Template
/** Bit template: single number via XOR fold. */
export function singleNumber(nums: number[]): number {
  let x = 0;
  for (const v of nums) x ^= v;
  return x;
}
/** Bit template: single number via XOR fold. */
export function singleNumber(nums: number[]): number {
  let x = 0;
  for (const v of nums) x ^= v;
  return x;
}
#StatusProblemTypeDone
  1. 1#136 Single NumberGuide
  2. 2#191 Number of 1 BitsGuide
  3. 3#231 Power of TwoGuide
  4. 4#268 Missing NumberGuide
  5. 5#338 Counting BitsGuide
  6. 6#371 Sum of Two IntegersGuide