Pattern #25
Bit Manipulation
RecommendedXOR, 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
- Map the problem to a bitwise identity.
- Watch language-specific int size.
- Prefer bit tricks over O(n) scans when the identity is clear.
- 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;
}
#StatusProblemTypeDifficultyDone
- 1#136 Single NumberGuideeasy
- 2#191 Number of 1 BitsGuideeasy
- 3#231 Power of TwoGuideeasy
- 4#268 Missing NumberGuideeasy
- 5#338 Counting BitsGuideeasy
- 6#371 Sum of Two IntegersGuidemedium