Bit Manipulation — Master Recap and Interview Cheatsheet

Sanjeev SharmaSanjeev Sharma
5 min read

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 check

XOR Properties Summary

PropertyExpressionUse Case
Self-cancela ^ a = 0Eliminate duplicates
Identitya ^ 0 = aAccumulate without altering
Commutativea ^ b = b ^ aOrder does not matter
Associative(a^b)^c = a^(b^c)Regroup freely
Find missingXOR all expected + actualMissing Number (LC 268)
Find singleXOR 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 3

Language 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').length

When to Reach for Bit Manipulation

SignalTechnique
Find one unique in array of doublesXOR accumulator
Find one unique in array of triplesones/twos state machine
Count set bits efficientlyBrian Kernighan loop
Check if n is a power of 2n and (n & (n-1)) == 0
Enumerate all subsets of a setBitmask from 0 to (1&lt;&lt;n)-1
State with small integer count (n <= 20)Bitmask DP
Maximize XOR of two numbersBinary trie (MSB to LSB)
Need O(1) space duplicate detectionXOR cancellation

Complexity Reference

PatternTimeSpace
XOR cancelO(n)O(1)
Brian KernighanO(log n) per numberO(1)
Bitmask DPO(2^n * n)O(2^n)
Subset enumerationO(3^n) totalO(1)
Binary trie XORO(32 * n)O(32 * n)
Bit reversalO(32)O(1)

Problem Index

PatternProblems
XOR cancelSingle Number I (01), Missing Number (07), Single Number III (03), Find Difference (08)
3-state bitsSingle Number II (02)
Brian KernighanNumber of 1 Bits (04)
Bit DP (easy)Counting Bits (05)
Bit reversalReverse Bits (06)
Bitmask enumerateSubsets (12), Product of Word Lengths, DNA Sequences
Bitmask DPPartition K Subsets (17), Min XOR Sum (16)
Bit tricksSum without + (10), Bitwise AND Range (14), Divide Integers (15)
Binary trieMaximum XOR of Two Numbers (11)

Key Takeaways

  • Two identities power everything in XOR problems: a ^ a = 0 (self-cancellation) and a ^ 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) & mask visits 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

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro

Related reading