Lesson 35 of 40DP families
Bitmask DP and DP on Trees
Use a bitmask as DP state when n is 20 or less, and return small tuples from each tree node to solve tree problems in one pass.
A delivery planner has 14 stops to visit and wants the shortest route. A scheduler has 12 engineers and 12 on-call slots, each pairing with a different cost. A network team wants the fewest monitors that watch every machine in a tree-shaped topology. Brute force on the first two is n factorial, which stops being feasible somewhere around 11. The third looks like it needs search. All three fall to DP once you pick the right state: for the first two the state is which items are used, stored as the bits of an integer, and for the third it is a small tuple returned by each subtree. This lesson covers both, plus two ideas you should recognise even if you never code them under pressure: rerooting and digit DP.
The constraint tell: n is at most 20
When a problem says n <= 16 or n <= 20, that number is a hint. You cannot afford n factorial (20! is about 2.4 × 10^18), but you can afford 2^n: 2^20 is about a million. A bitmask DP has one state per subset, and usually multiplies that by n (which element was last) and by n again for the transition. 2^20 × 20 is about 20 million steps, fine in most languages and workable in Python. 2^20 × 20 × 20 is 400 million, too slow in Python.
The subset lives in an integer. Bit i is 1 when item i is in the set. You met the operators in Bit Manipulation; here is how they read as set operations:
| Code | Meaning |
|---|---|
mask & (1 << i) | is item i in the set? (non-zero means yes) |
mask | (1 << i) | add item i |
mask & ~(1 << i) | remove item i |
bin(mask).count("1") | how many items (int.bit_count() since Python 3.10) |
(1 << n) - 1 | the full set: all n bits on |
range(1 << n) | every subset, smallest first |
Looping for mask in range(1 << n) visits every subset in increasing numeric order. That order has a useful property: adding a bit always makes the number bigger, so mask | (1 << i) is always after mask. If your transitions only add items, a single forward loop is a valid fill order.
What does this print?
mask = 0b0110 print([i for i in range(4) if mask & (1 << i)], mask | (1 << 0), mask & ~(1 << 2))
Enumerating the subsets of a mask
Some problems need every subset of a given mask (split a group into two teams, or pick which subset to handle next). The trick is sub = (sub - 1) & mask. Subtracting 1 clears the lowest set bit and sets everything below it, and the & mask throws away bits that are not in the mask. The result walks down through every submask in decreasing order.
Start at the mask itself: items 0, 1 and 3. The boxes show bits 3, 2, 1, 0 from left to right.
Press Run (⌘ Enter) to see what happens.Looping over every mask and then every submask of it costs 3^n in total, not 4^n: each item is either out of the mask, in the mask but out of the submask, or in both. 3^16 is about 43 million, so "for every subset, try every way to split it" is realistic up to about n = 16.
Assignment: dp over the set of used jobs
n workers, n jobs, cost[w][j] for worker w doing job j. Give each worker one job at the lowest total cost.
The insight is that you do not need to remember who got which job. If workers are placed in order 0, 1, 2…, then the number of jobs already taken tells you which worker is next. So the state is just the set of taken jobs: dp[mask] = cheapest way to give the jobs in mask to the first popcount(mask) workers. That is 2^n states instead of n! orderings.
Press Run (⌘ Enter) to see what happens.O(2^n × n). In production you would reach for the Hungarian algorithm, which is O(n^3) and handles hundreds of workers. The bitmask version matters because it generalises: when the assignment has extra rules (some jobs must be done together, a worker can take two jobs), the Hungarian algorithm stops applying and the mask DP still works.
Routes: dp[mask][last]
The travelling salesman problem asks for the shortest loop through every city. Here "which cities are visited" is not enough state, because the cost of the next step depends on where you are now. So the state grows to dp[mask][last]: the shortest path that starts at city 0, visits exactly the cities in mask, and ends at last. This is the Held-Karp algorithm, O(2^n × n^2). That is still exponential, but 2^15 × 225 is about 7 million, while 15! is over a trillion.
Press Run (⌘ Enter) to see what happens.Shortest Path Visiting All Nodes is the unweighted cousin, and it changes the tool. Every edge costs 1, so instead of a DP table you run BFS over states (node, mask). You may revisit nodes, which is why node alone is not a valid "seen" key: the same node with a different visited set is a different state. Start from every node at once (multi-source BFS), because the path may begin anywhere.
Press Run (⌘ Enter) to see what happens.The same "put the mask in the BFS state" move solves grid puzzles with keys and locked doors: the state is (row, col, keys_held).
Memo on a mask: partitions and games
Partition to K Equal Sum Subsets: can you split nums into k groups with equal sums? The backtracking solution from Backtracking works, but it repeats work, because the same set of used numbers can be reached in many orders. A mask DP visits each set once.
Fill the groups one at a time. Because groups fill in order, the state does not need to record which group each number went to, only how full the current group is. And that is fixed by the mask: it is sum(mask) % target. So fill[mask] is either that value (reachable) or -1 (no valid way to use exactly these numbers).
Press Run (⌘ Enter) to see what happens.Can I Win is a game: players take turns picking unused numbers from 1 to max_choice, and whoever pushes the running total to desired wins. The position is fully described by the set of used numbers, because remaining follows from it. A position is a win if some move either reaches the total or leaves the opponent in a losing position. Top-down with @cache fits here because many masks are never reached, and the recursion is at most max_choice (20) deep, so the recursion limit is not a concern. The early exit matters: if all the numbers together cannot reach desired, nobody wins, and the search would otherwise wrongly report a loss for the first player.
DP on trees: return a tuple per node
Tree DP rarely needs a table. The subtree is the subproblem, and a post-order traversal computes children before parents, which is exactly the fill order you need. The skill is deciding what each node returns. Return one number and you often lose information the parent needs. Return a small tuple, one value per "state" of the node, and the parent can combine them.
House Robber III: houses form a binary tree, and you cannot rob a node and its direct child. For each node return (rob, skip):
rob= this node's value +skipof each child (children must be left alone).skip= for each child, the better of itsrobandskip(they are free to choose).
No robbing a node together with its child. Each node will report two numbers: best if robbed, best if skipped.
Press Run (⌘ Enter) to see what happens.O(n) time, and O(height) stack. The common wrong answer memoises a function that returns one number and recurses into grandchildren. It works, but it is slower and harder to reason about than returning two values.
Binary Tree Cameras: place the fewest cameras so every node is watched, where a camera watches itself, its parent and its children. Each node reports one of three states: NEEDS (not watched yet), CAMERA (has one), or COVERED (watched, no camera). The rule is greedy but justified: never put a camera on a leaf, because its parent covers everything the leaf would and more. So decisions flow upward.
Press Run (⌘ Enter) to see what happens.Two details catch people. A None child must report COVERED, or every leaf would demand a camera from its parent for a child that does not exist. And the root needs a final check, because nobody above it can fix a NEEDS.
Rerooting: every node as the root
Sum of Distances in Tree asks, for every node, the sum of its distances to all other nodes. Running a BFS from each node is O(n^2). Rerooting does it in O(n) with two passes:
- Root the tree at node 0. Going leaves-up, compute
size[u](nodes in u's subtree) anddown[u](sum of distances from u to its subtree).down[parent] += down[child] + size[child], because each of the child's nodes is one step further from the parent. ans[0] = down[0]. Going root-down, move the root across one edge from parentpto childu. Thesize[u]nodes in u's subtree each get 1 closer, and the othern - size[u]nodes each get 1 further:ans[u] = ans[p] - size[u] + (n - size[u]).
Press Run (⌘ Enter) to see what happens.Rerooting is rare in interviews and common in competitive programming. Recognise it when a problem asks for a tree answer "for every node" and the one-root answer is a simple tree DP. You will not usually be asked to invent it on the spot, but naming it and sketching the two passes is a strong signal.
Digit DP, in one paragraph
"How many integers from 1 to N have no repeated digits?" or "…have a digit sum divisible by 7?" N can be 10^18, so you cannot loop. Digit DP builds the number one digit at a time from the most significant end, with a state like (position, tight, extra): tight says whether the digits so far equal N's prefix (so the next digit is capped by N's digit), and extra is whatever the property needs (a mask of used digits, a running sum mod 7). The count is a memoised walk over about digits × 2 × extra × 10 states. Recognise it from "count numbers up to N with a property" where N is huge, and say so. It is rare in standard interviews.
Match each problem to the state that solves it.
Order these running times from slowest-growing to fastest-growing. They decide how large n can be.
- Tap the steps below in the right order.
- bitmask
- An integer whose bits mark which items are in a set. Bit i is on when item i is included.
- submask enumeration
- Visit every subset of mask with sub = (sub - 1) & mask. Over all masks it costs 3^n.
- Held-Karp
- The dp[mask][last] algorithm for TSP. O(2^n n^2) instead of O(n!).
- tree DP
- DP where each node's answer is computed from its children's, in post-order, often as a small tuple of states.
- rerooting
- Compute a tree answer for one root, then shift the root across each edge in O(1) to get every node's answer in O(n).
- digit DP
- Count numbers up to N with a property by building them digit by digit with a tight flag.