Bit Tricks & Bitmasking
O(n)
XOR cancels pairs; x & (x−1) drops the lowest set bit; a mask enumerates subsets compactly.
0/55 solved
Recognise it
The signal
"Every element appears twice except one", count set bits, power of two, add without
+, or small subsets encoded as integer masks.
1Brute force
Hash maps or arithmetic loops.
2The observation
Extra memory/time: bits are processed in parallel and XOR is its own inverse.
3Why it works
a ^ a = 0,a ^ 0 = a, XOR commutes, and each bit position is independent under XOR/AND/OR.
Reach for it when
- +XOR cancellation — single number, missing number, two swapped values, find the duplicate.
- +Counting / parity of bits — popcount, counting bits 0..n, powers of two.
- +Encoding small sets as integer masks (also see Bitmask DP), or arithmetic without operators.
Not when
- ×Large/continuous values where you need ranking or sumsuse Arrays or heaps
- ×Set too big for a mask (>64 items to store, >~20 to enumerate 2ⁿ)use A real set
- ×It looks numeric but needs ordering or searchuse Binary search or hashing
- ×Arithmetic carries mix bits, so per-bit reasoning failsuse Ordinary arithmetic reasoning
- ×You're enumerating subset states for an optimum under small nuse Bitmask DP
Intuition
Numbers are stored as bits — a row of on/off switches (powers of two). Bit tricks manipulate those switches directly, which is fast and sometimes the only O(1)-space way.
Read the full intuition
Four switches you must own:
- XOR (^) — a "toggle."
a ^ a = 0(same thing twice cancels),a ^ 0 = a. XOR a whole list and every value appearing an even number of times vanishes — the odd-one-out survives. That's Single Number in one line. - AND (&) — masks/tests bits.
x & 1reads the lowest bit;x & (x-1)clears the lowest set bit (the heart of fast popcount). - OR (|) — sets bits. Shift (<<, >>) — multiply/divide by powers of two, or move a mask to bit
bwith1 << b.
Walk Single Number on [4,1,2,1,2]: XOR running total goes 0→4→5→7→6→4. The two 1s cancel, the two 2s cancel, 4 remains.
Key idea
Most bit problems are one of: XOR cancellation (single/missing/swapped), per-bit counting (when duplicates come in 3s or k's, tally each bit mod k), or low-bit manipulation (
x & -xisolates the lowest set bit;x & (x-1)clears it).
Why it costs what it costs
Time O(n) or O(32·n). XOR is a single pass; per-bit counting is 32 passes (constant factor); popcount is O(set bits).
Space O(1). a few integer accumulators — the whole appeal over hashing/sorting.
Practice
- Number of 1 BitsFoundationFoundationAmazon, AdobeEasy
- Single NumberApply it · Pairs cancel.Apply itAmazon, AdobeEasy
- Power of TwoOne change · Single set bit test.One changeAdobe, AppleEasy
- Counting BitsOne change · Bits for all numbers.One changeAmazon, AdobeEasy
- Single Number IITwists · Triples instead of pairs.TwistsAmazon, CitadelMedium
- Single Number IIIBranches · Two unique numbers.BranchesAmazon, CitadelMedium
- Sum of Two IntegersBranches · No + operator.BranchesApple, AdobeMedium
- Bitwise AND of Numbers RangeBranches · Range AND.BranchesAdobe, AmazonMedium
- Maximum Product of Word LengthsCombine · Sets of letters as masks.CombineMedium
- Counting BitsMastery checkMastery checkCSESMedium
- Reverse BitsApple, AdobeEasy
- Add BinaryMeta, AmazonEasy
Pitfalls
Classic bugs
- !Width: JS bitwise is 32-bit signed (use
>>>,| 0); Python ints are unbounded (mask& 0xFFFFFFFF). - !Precedence:
x & 1 == 0isx & (1==0). Write(x & 1) == 0. - !Right-shifting negatives is arithmetic (sign-filling) — use unsigned shift or mask first.
- !Sum trick
2·sum(set) − sum(all)overflows and only fits 'exactly twice'; use XOR or per-bit counts (any k). - !
x & (x-1)clears the lowest set bit;x & -xisolates it. Kernighan loops once per set bit, not 32. - !Single Number III: XOR all, split by the result's lowest set bit, XOR each group.
- !Add without
+: sum =a ^ b, carry =(a & b) << 1, repeat until carry is 0.
Go deepervariants and techniques · 9 combinations · interviewer follow-ups · resources
Variants and techniques
- XOR Linear Basis (Gaussian elimination over GF(2))Reduce numbers to at most B independent vectors over GF(2) to answer max subset XOR, count distinct subset XORs, or membership.
- Bitset OptimisationCP 2000Pack boolean DP rows or adjacency sets into machine words, so one AND/OR/shift handles 64 states at once. O(n*W) becomes O(n*W/64).
- Few Distinct Subarray OR / AND / GCD ValuesInterview · hardFor a fixed right end i, the OR (AND, GCD) of a[j..i] changes at most log2(V) times as j moves left, because each change adds a bit (removes a bit, or at least halves the gcd). Keep the list of (value, leftmost j) for i - 1 and extend it to i.
- XOR cancellationXOR the list; pairs vanish. Single Number, Missing Number.
- Per-bit mod-k countingCount each bit position mod k for k-repeats. Single Number II.
- Split by a differing bitXOR all, isolate a set bit, partition, XOR each half. Single Number III.
- Low-bit tricks
x&(x-1)clears,x&-xisolates — popcount, power-of-two tests. Number of 1 Bits, Power of Two. - Bit DP / arithmeticbits[i]=bits[i>>1]+(i&1); add via xor/carry. Counting Bits, Sum of Two Integers.
Combinations
Sum over Subsets (SOS) DP+Bit Tricks & Bitmasking
for each x count y with x | y == x, x & y == y, or x & y == 0
- Sum over Subsets (SOS) DP:
- aggregates over submasks for all masks
- Bit Tricks & Bitmasking:
- mask representation
Backtracking+Bit Tricks & Bitmasking
N-Queens, Sudoku, placement puzzles
- Backtracking:
- the search
- Bit Tricks & Bitmasking:
- O(1) constraint sets as bitmasks
Prefix Sum+Bit Tricks & Bitmasking+Hash Map / Hash Set Lookup
substrings/subarrays where every letter (or bit) occurs an even number of times, or at most one is odd
- Prefix Sum:
- a substring's parity is prefix[j] ^ prefix[i]
- Bit Tricks & Bitmasking:
- a parity mask of the character counts replaces a count vector
- Hash Map / Hash Set Lookup:
- first index (or count) of each mask seen so far
Find the Longest Substring Containing Vowels in Even CountsNumber of Wonderful SubstringsCount the Number of Beautiful Subarrays
Bitset Optimisation+Topological Sort
for every vertex of a DAG with n ~ 5e4, the number of vertices reachable from it
- Bitset Optimisation:
- reach[v] = {v} | OR of reach[child], 64 vertices per word
- Topological Sort:
- process vertices in reverse topological order
Strongly Connected Components & Condensation+Topological Sort+Bitset Optimisation
many 'can a reach b' queries on a general directed graph with n ~ 5e4
- Strongly Connected Components & Condensation:
- condense cycles so reachability lives on a DAG
- Topological Sort:
- an order for the DP over components
- Bitset Optimisation:
- per-component reachability sets
Few Distinct Subarray OR / AND / GCD Values+Hash Map / Hash Set Lookup
distinct subarray ORs, or the number of subarrays with AND equal to k
- Few Distinct Subarray OR / AND / GCD Values:
- at most log V distinct OR/AND values end at each index
- Hash Map / Hash Set Lookup:
- collect the distinct values, or count those equal to k
Bitwise ORs of SubarraysNumber of Subarrays With AND Value of K
Few Distinct Subarray OR / AND / GCD Values+GCD / LCM & Euclid+Hash Map / Hash Set Lookup
the number of subarrays whose gcd equals x, for many x
- Few Distinct Subarray OR / AND / GCD Values:
- O(log V) (gcd, count) pairs per right end
- GCD / LCM & Euclid:
- the gcd as j moves left only drops to a divisor
- Hash Map / Hash Set Lookup:
- global count of subarrays per gcd value
Bitset Optimisation+0/1 Knapsack
which totals are reachable, values up to 5e4, n up to 5e4
- Bitset Optimisation:
- a shift-or over word-packed bits
- 0/1 Knapsack:
- boolean reachability of sums
Union-Find (Disjoint Set)+Bitset Optimisation+0/1 Knapsack
split the vertices into two groups without breaking components, for every possible size
- Union-Find (Disjoint Set):
- component sizes
- Bitset Optimisation:
- makes the subset sum fast
- 0/1 Knapsack:
- which totals of component sizes are achievable
Follow-ups interviewers ask
- 01What if each number appears k times except one? → tally each bit count mod k (the state-machine variant).
- 02What if two numbers are unique? → XOR all, isolate a differing bit (
d & -d), partition into two buckets, XOR each. - 03Add two integers without
+/-? → sum =a ^ b, carry =(a & b) << 1, repeat until carry is 0. - 04Count set bits for every number 0..n efficiently? → DP:
bits[i] = bits[i >> 1] + (i & 1)(Counting Bits).
State table
| n | binary | running XOR x |
|---|---|---|
| — | — | 000 (0) |
| 4 | 100 |
100 (4) |
| 1 | 001 |
101 (5) |
| 2 | 010 |
111 (7) |
| 1 | 001 |
110 (6) |
| 2 | 010 |
100 (4) → answer 4 |