Bitmask DP
O(2ⁿ · n)
Encode the set of used/visited elements as an integer bitmask and memoize over (mask, position).
0/16 solved
Recognise it
The signal
Tiny n (<= ~20, sometimes 15-16 with an extra factor); visit/assign/order everything: TSP, Hamiltonian path, k-partition.
1Brute force
Try all n! orders.
2The observation
n! orders collapse to 2n subsets: the future depends only on the set used (and the last item).
3Why it works
dp[mask][last] is optimal over orderings of exactly the items in mask, ending at last.
Reach for it when
- +visit/assign/order a small set
- +Hamiltonian path / TSP
Not when
- ×n > ~25, 2ⁿ blows upuse Meet in the middle, or greedy
- ×Items are interchangeable, so counts sufficeuse Knapsack-style DP over counts
Practice
- Can I WinFoundationFoundationMedium
- Partition to K Equal Sum SubsetsApply it · dp[mask] = fill of current bucket.Apply itAmazon, CitadelMedium
- Hamiltonian FlightsOne change · Hamiltonian paths count.One changeCSESHard
- Find the Shortest SuperstringOne change · TSP with overlap costs plus reconstruction.One changeHard
- Shortest Path Visiting All NodesTwists · Revisits allowed; edges unweighted.TwistsHard
- Elevator RidesBranches · State holds a pair (rides, last load).BranchesCSESMedium
- Maximum Students Taking ExamBranches · Masks are rows of a grid.BranchesHard
- Parallel Courses IIAdvanced · Greedy topological picking is wrong.AdvancedHard
- Counting TilingsMastery checkMastery checkCSESHard
- SOS Bit ProblemCSESMedium
- And Subset CountCSESHard
- Compatible NumbersCodeforces2200
Pitfalls
Classic bugs
- !Mixing up 'mask of used' with 'mask of available': pick one meaning and keep it in every transition.
- !Increasing mask order is a valid fill order: adding a bit always makes a bigger number, so sources are done first.
Go deepervariants and techniques · 6 combinations · resources
Variants and techniques
Combinations
shortest walk visiting all nodes/keys with n <= 12-20
- Graph BFS / DFS:
- BFS over moves
- Bitmask DP:
- encodes visited set into the state
Bitmask DP+String Matching (KMP / Z / Rabin-Karp)
shortest superstring containing all words (n <= 12)
- Bitmask DP:
- TSP over strings
- String Matching (KMP / Z / Rabin-Karp):
- pairwise overlaps; with at most 12 short words brute force is enough, borders (KMP) only matter at larger sizes
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
Combinatorial Game Theory (minimax, Nim, Sprague-Grundy)+Bitmask DP
two players pick from a small pool (n <= 20) without replacement
- Combinatorial Game Theory (minimax, Nim, Sprague-Grundy):
- a state is winning if some move leads to a losing state
- Bitmask DP:
- the set of used numbers is the state
count numbers <= N with all distinct (or repeated) digits
- Digit DP:
- the tight-prefix walk over the digits of N
- Bitmask DP:
- mask of digits already used
Randomised Sampling Arguments+Sum over Subsets (SOS) DP
find the largest set of items liked by at least half the people, with m <= 60 items but <= 15 liked per person
- Randomised Sampling Arguments:
- a random friend belongs to the optimal half-liked set with probability >= 1/2
- Sum over Subsets (SOS) DP:
- for that friend's <= 15 liked currencies, count supersets over masks