Bit Manipulation — Master Recap and Interview Cheatsheet
Advertisement
Bit Manipulation Master Cheatsheet
Quick-reference for every bit trick, template, and pattern covered in this series.
Essential Tricks
n & (n-1) # Remove lowest set bit (Brian Kernighan)
n & (-n) # Isolate lowest set bit
n | (n-1) # Set all bits below lowest 1
~n + 1 # Two's complement (negation)
n ^ n # == 0: XOR self-cancellation
n ^ 0 # == n: XOR identity element
(n >> i) & 1 # Get bit i
n | (1 << i) # Set bit i
n & ~(1 << i) # Clear bit i
n ^ (1 << i) # Toggle bit i
n & (n-1) == 0 and n > 0 # Power of 2 checkXOR Properties Summary
| Property | Expression | Use Case |
|---|---|---|
| Self-cancel | a ^ a = 0 | Eliminate duplicates |
| Identity | a ^ 0 = a | Accumulate without altering |
| Commutative | a ^ b = b ^ a | Order does not matter |
| Associative | (a^b)^c = a^(b^c) | Regroup freely |
| Find missing | XOR all expected + actual | Missing Number (LC 268) |
| Find single | XOR all (duplicates cancel) | Single Number (LC 136) |
Bitmask DP Template
dp = [float('inf')] * (1 << n)
dp[0] = 0
for mask in range(1 << n):
i = bin(mask).count('1') # number of assigned items so far
for j in range(n):
if not (mask & (1 << j)): # j not yet used
new_mask = mask | (1 << j)
dp[new_mask] = min(dp[new_mask], dp[mask] + cost(i, j))Subset Enumeration Template
sub = mask
while sub:
process(sub)
sub = (sub - 1) & mask # next smaller subset of mask
# Total iterations across all masks: O(3^n)3-State Bit Counter (mod 3) Template
# For k=3 appearances: use ones/twos bitmasks
ones, twos = 0, 0
for n in nums:
ones = (ones ^ n) & ~twos # update ones using old twos
twos = (twos ^ n) & ~ones # update twos using new ones
# ones holds bits seen exactly once mod 3Language Popcount Reference
# Python
bin(n).count('1')
# C/C++
__builtin_popcount(n)
# Java
Integer.bitCount(n)
# JavaScript
n.toString(2).split('').filter(x => x === '1').lengthWhen to Reach for Bit Manipulation
| Signal | Technique |
|---|---|
| Find one unique in array of doubles | XOR accumulator |
| Find one unique in array of triples | ones/twos state machine |
| Count set bits efficiently | Brian Kernighan loop |
| Check if n is a power of 2 | n and (n & (n-1)) == 0 |
| Enumerate all subsets of a set | Bitmask from 0 to (1<<n)-1 |
| State with small integer count (n <= 20) | Bitmask DP |
| Maximize XOR of two numbers | Binary trie (MSB to LSB) |
| Need O(1) space duplicate detection | XOR cancellation |
Complexity Reference
| Pattern | Time | Space |
|---|---|---|
| XOR cancel | O(n) | O(1) |
| Brian Kernighan | O(log n) per number | O(1) |
| Bitmask DP | O(2^n * n) | O(2^n) |
| Subset enumeration | O(3^n) total | O(1) |
| Binary trie XOR | O(32 * n) | O(32 * n) |
| Bit reversal | O(32) | O(1) |
Problem Index
| Pattern | Problems |
|---|---|
| XOR cancel | Single Number I (01), Missing Number (07), Single Number III (03), Find Difference (08) |
| 3-state bits | Single Number II (02) |
| Brian Kernighan | Number of 1 Bits (04) |
| Bit DP (easy) | Counting Bits (05) |
| Bit reversal | Reverse Bits (06) |
| Bitmask enumerate | Subsets (12), Product of Word Lengths, DNA Sequences |
| Bitmask DP | Partition K Subsets (17), Min XOR Sum (16) |
| Bit tricks | Sum without + (10), Bitwise AND Range (14), Divide Integers (15) |
| Binary trie | Maximum XOR of Two Numbers (11) |
Key Takeaways
- Two identities power everything in XOR problems:
a ^ a = 0(self-cancellation) anda ^ 0 = a(identity element). - Brian Kernighan's
n & (n-1)removes exactly one set bit per iteration — count iterations to count bits. n & (-n)isolates the rightmost set bit — used in BIT updates, subset enumeration, and partitioning arrays.- Bitmask DP encodes exponential state in a single integer; feasible up to n = 20, runs in O(2^n * n).
- Subset enumeration with
sub = (sub-1) & maskvisits every subset of a bitmask exactly once in O(3^n) total. - For k-times duplicates, you need
ceil(log2(k))bitmasks: XOR (k=2) uses 1, mod-3 (k=3) uses 2 (ones and twos). - Bit manipulation is the go-to when a problem explicitly requires O(1) space and duplicates need to cancel.
Advertisement
Related reading
Bit Manipulation Tricks Explained — XOR Patterns, Subset Enumeration, Bitmask DP [LC 136, Google, Meta]8 min readTries — Master Recap and Interview Cheatsheet5 min readArrays & Strings Complete — 100-Problem Master Cheatsheet6 min readBinary Search Master Recap — All Patterns, Templates & FAANG Cheatsheet8 min readBFS & DFS Graphs — Master Recap & Cheatsheet4 min readGreedy and Monotonic Stack — Master Recap and Cheatsheet6 min read