Skip to content

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.

28 min read0/5 questions

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:

CodeMeaning
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) - 1the 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.

Predict the outputPython

What does this print?

mask = 0b0110
print([i for i in range(4) if mask & (1 << i)], mask | (1 << 0), mask & ~(1 << 2))
Need a nudge? Hints walk you through it.

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.

Submasks of 1011 with sub = (sub - 1) & mask
1
0
0
1
1
2
1
3
sub = 1011 (11)

Start at the mask itself: items 0, 1 and 3. The boxes show bits 3, 2, 1, 0 from left to right.

1/6
Python
mask = 0b1011sub = maskseen = []while True: seen.append(format(sub, "04b")) if sub == 0: break sub = (sub - 1) & maskprint(seen)assert len(seen) == 2 ** bin(mask).count("1") # Every (mask, submask) pair over n bits: 3^n, not 4^nn = 4pairs = 0for m in range(1 << n): s = m while True: pairs += 1 if s == 0: break s = (s - 1) & massert pairs == 3 ** nprint(pairs)
Output
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.

Python
from itertools import permutations def min_assignment(cost): n = len(cost) INF = float("inf") dp = [INF] * (1 << n) # dp[mask]: best cost when the jobs in mask are taken dp[0] = 0 for mask in range(1 << n): if dp[mask] == INF: continue worker = bin(mask).count("1") # workers 0..worker-1 are already placed if worker == n: continue for job in range(n): if not mask & (1 << job): nxt = mask | (1 << job) dp[nxt] = min(dp[nxt], dp[mask] + cost[worker][job]) return dp[(1 << n) - 1] def brute(cost): n = len(cost) return min(sum(cost[w][p[w]] for w in range(n)) for p in permutations(range(n))) cost = [[9, 2, 7, 8], [6, 4, 3, 7], [5, 8, 1, 8], [7, 6, 9, 4]]assert min_assignment(cost) == brute(cost) == 13assert min_assignment([[5]]) == 5print(min_assignment(cost))
Output
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.

Python
from itertools import permutations def tsp(dist): n = len(dist) INF = float("inf") full = (1 << n) - 1 # dp[mask][last]: shortest path that starts at city 0, visits exactly mask, ends at last dp = [[INF] * n for _ in range(1 << n)] dp[1][0] = 0 for mask in range(1 << n): if not mask & 1: continue # every path starts at city 0 for last in range(n): d = dp[mask][last] if d == INF: continue for nxt in range(n): if mask & (1 << nxt): continue m2 = mask | (1 << nxt) if d + dist[last][nxt] < dp[m2][nxt]: dp[m2][nxt] = d + dist[last][nxt] return min(dp[full][last] + dist[last][0] for last in range(n)) # close the loop def brute(dist): n = len(dist) best = float("inf") for order in permutations(range(1, n)): route = (0,) + order + (0,) best = min(best, sum(dist[a][b] for a, b in zip(route, route[1:]))) return best dist = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]assert tsp(dist) == brute(dist) == 80d5 = [[0, 3, 4, 2, 7], [3, 0, 4, 6, 3], [4, 4, 0, 5, 8], [2, 6, 5, 0, 6], [7, 3, 8, 6, 0]]assert tsp(d5) == brute(d5)print(tsp(dist), tsp(d5))
Output
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.

Python
from collections import deque def shortest_path_all_nodes(graph): n = len(graph) full = (1 << n) - 1 # start from every node at once, each with only itself visited queue = deque((node, 1 << node, 0) for node in range(n)) seen = {(node, 1 << node) for node in range(n)} while queue: node, mask, dist = queue.popleft() if mask == full: return dist for nb in graph[node]: state = (nb, mask | (1 << nb)) if state not in seen: seen.add(state) queue.append((nb, state[1], dist + 1)) return -1 assert shortest_path_all_nodes([[1, 2, 3], [0], [0], [0]]) == 4assert shortest_path_all_nodes([[1], [0, 2, 4], [1, 3, 4], [2], [1, 2]]) == 4assert shortest_path_all_nodes([[]]) == 0print(shortest_path_all_nodes([[1, 2, 3], [0], [0], [0]]))
Output
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).

Python
from functools import cache def can_partition_k(nums, k): total = sum(nums) if total % k: return False target = total // k nums = sorted(nums, reverse=True) if nums[0] > target: return False n = len(nums) # fill[mask]: how full the current bucket is after using mask, or -1 if unreachable fill = [-1] * (1 << n) fill[0] = 0 for mask in range(1 << n): if fill[mask] < 0: continue for i in range(n): if mask & (1 << i): continue if fill[mask] + nums[i] > target: continue nxt = mask | (1 << i) if fill[nxt] < 0: fill[nxt] = (fill[mask] + nums[i]) % target # a full bucket wraps to 0 return fill[(1 << n) - 1] == 0 def can_i_win(max_choice, desired): if desired <= 0: return True if max_choice * (max_choice + 1) // 2 < desired: return False # even using every number, nobody reaches the total @cache def wins(used, remaining): for x in range(1, max_choice + 1): bit = 1 << x if used & bit: continue if x >= remaining or not wins(used | bit, remaining - x): return True return False return wins(0, desired) assert can_partition_k([4, 3, 2, 3, 5, 2, 1], 4) is Trueassert can_partition_k([1, 2, 3, 4], 3) is Falseassert can_partition_k([2, 2, 2, 2, 3, 4, 5], 4) is Falseassert can_i_win(10, 11) is Falseassert can_i_win(10, 0) is Trueassert can_i_win(10, 1) is Trueassert can_i_win(4, 6) is Trueprint(can_partition_k([4, 3, 2, 3, 5, 2, 1], 4), can_i_win(10, 11))
Output
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.

Quick check
A problem gives n tasks with n up to 15 and asks for the cheapest order to run them, where the cost of each task depends on which tasks already ran AND on which task ran just before it. What state fits?
Need a nudge? A hint rules out a wrong answer.

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 + skip of each child (children must be left alone).
  • skip = for each child, the better of its rob and skip (they are free to choose).
House Robber III: (rob, skip) from the leaves up
146357

No robbing a node together with its child. Each node will report two numbers: best if robbed, best if skipped.

1/5
Python
class Node: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def build(values): """Level-order list (None = missing) to a tree, without recursion.""" if not values or values[0] is None: return None nodes = [None if v is None else Node(v) for v in values] kids = iter(nodes[1:]) for node in nodes: if node is None: continue node.left = next(kids, None) node.right = next(kids, None) return nodes[0] def rob(root): def best(node): """Return (rob this node, skip this node) for the subtree.""" if node is None: return (0, 0) l_rob, l_skip = best(node.left) r_rob, r_skip = best(node.right) take = node.val + l_skip + r_skip # children must be skipped leave = max(l_rob, l_skip) + max(r_rob, r_skip) # children are free to choose return (take, leave) return max(best(root)) assert rob(build([3, 4, 5, 1, 6, None, 7])) == 17 # 3 + 1 + 6 + 7assert rob(build([3, 2, 3, None, 3, None, 1])) == 7assert rob(build([3, 4, 5, 1, 3, None, 1])) == 9assert rob(build([])) == 0print(rob(build([3, 4, 5, 1, 6, None, 7])))
Output
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.

Python
class Node: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def build(values): if not values or values[0] is None: return None nodes = [None if v is None else Node(v) for v in values] kids = iter(nodes[1:]) for node in nodes: if node is None: continue node.left = next(kids, None) node.right = next(kids, None) return nodes[0] NEEDS, CAMERA, COVERED = 0, 1, 2 def min_cameras(root): count = 0 def state(node): nonlocal count if node is None: return COVERED # a missing child never needs watching left, right = state(node.left), state(node.right) if left == NEEDS or right == NEEDS: count += 1 return CAMERA # a child is exposed: put a camera here if left == CAMERA or right == CAMERA: return COVERED # a child's camera watches this node return NEEDS # leave it for the parent if state(root) == NEEDS: count += 1 # the root has no parent to cover it return count assert min_cameras(build([0, 0, None, 0, 0])) == 1assert min_cameras(build([0, 0, None, 0, None, 0, None, None, 0])) == 2assert min_cameras(build([0])) == 1assert min_cameras(build([0, 0, 0])) == 1print(min_cameras(build([0, 0, None, 0, None, 0, None, None, 0])))
Output
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.

Quick check
In Binary Tree Cameras, why is it safe to never put a camera on a leaf?
Need a nudge? A hint rules out a wrong answer.

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:

  1. Root the tree at node 0. Going leaves-up, compute size[u] (nodes in u's subtree) and down[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.
  2. ans[0] = down[0]. Going root-down, move the root across one edge from parent p to child u. The size[u] nodes in u's subtree each get 1 closer, and the other n - size[u] nodes each get 1 further: ans[u] = ans[p] - size[u] + (n - size[u]).
Python
from collections import deque def sum_of_distances(n, edges): adj = [[] for _ in range(n)] for a, b in edges: adj[a].append(b) adj[b].append(a) # BFS order from root 0: parents always appear before children parent = [-1] * n order = [] seen = [False] * n seen[0] = True queue = deque([0]) while queue: u = queue.popleft() order.append(u) for v in adj[u]: if not seen[v]: seen[v] = True parent[v] = u queue.append(v) # pass 1, leaves up: subtree sizes and distance sum for root 0 size = [1] * n down = [0] * n # down[u]: sum of distances from u to nodes in its subtree for u in reversed(order): p = parent[u] if p >= 0: size[p] += size[u] down[p] += down[u] + size[u] # pass 2, root down: move the root across one edge at a time ans = [0] * n ans[0] = down[0] for u in order[1:]: p = parent[u] ans[u] = ans[p] - size[u] + (n - size[u]) return ans def brute(n, edges): adj = [[] for _ in range(n)] for a, b in edges: adj[a].append(b) adj[b].append(a) out = [] for s in range(n): dist = {s: 0} q = deque([s]) while q: u = q.popleft() for v in adj[u]: if v not in dist: dist[v] = dist[u] + 1 q.append(v) out.append(sum(dist.values())) return out edges = [[0, 1], [0, 2], [2, 3], [2, 4], [2, 5]]assert sum_of_distances(6, edges) == [8, 12, 6, 10, 10, 10] == brute(6, edges)assert sum_of_distances(1, []) == [0]line = [[i, i + 1] for i in range(300)] # a long path: no recursion, no stack overflowassert sum_of_distances(301, line) == brute(301, line)print(sum_of_distances(6, edges))
Output
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 the pairs0/5 matched

Match each problem to the state that solves it.

Choose an item, then its match on the other side.
Put it in order4 steps

Order these running times from slowest-growing to fastest-growing. They decide how large n can be.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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.