Once you are comfortable with 1D and 2D tables, the remaining DP families differ mainly in what the state looks like: a range [i, j] (interval DP), a subset encoded as bits (bitmask DP), a node of a tree (tree DP), a mode such as "holding a stock" (state-machine DP), or a position in a number's digits (digit DP). Each family has a recognizable signal, a standard loop shape and a typical complexity. This page tours all of them, then sketches the optimizations used when even a correct DP is too slow.
Think of it like
Designing a video game save file
When a game saves your progress it does not record every move you made, only what matters for the future: the level, your inventory, your health. Designing a DP state is the same job. For a stock problem the save file is "day and whether I hold a share"; for a traveling salesman it is "which cities I have visited and where I am now"; for burst balloons it is "which stretch of balloons is still in play". Pick the right save file and the rest is bookkeeping.
The common thread: designing the state
A good state captures exactly the information about the past that affects future decisions, and nothing more. If two different histories leave you in the same state, the best way to finish must be the same for both: that is what lets DP reuse answers. Most "hard" DP problems are hard only because the right state is not obvious.
| Pattern | Typical state | Transition | Typical cost | Signal in the problem |
|---|---|---|---|---|
| Interval | dp[i][j] for a range | Try every split point or last action k | O(n³) | Merging, bursting, cutting or parenthesizing a sequence; order of operations matters |
| Bitmask | dp[mask] or dp[mask][v] | Add one element to the set | O(2ⁿ·n) to O(2ⁿ·n²) | n ≤ 20; visit all, assign all, choose subsets |
| Tree | dp[node][flag] | Combine children in post-order | O(n) | Input is a tree; choose nodes or paths with local constraints |
| State machine | dp[i][mode] | Move between a few modes per step | O(n·modes) | Holding/not holding, cooldowns, limited transactions |
| Digit | dp[pos][tight][extra] | Choose the next digit | O(digits·10·extra) | Count integers in [L, R] with a digit property |
Interval DP
Interval DP solves a problem on a contiguous range [i, j] by combining answers on smaller ranges inside it. The table is indexed by both endpoints, and cells are filled by increasing interval length, so every sub-interval is ready before it is needed.
for length in range(2, n + 1): # short intervals first
for i in range(0, n - length + 1):
j = i + length - 1
dp[i][j] = INF
for k in range(i, j): # every way to split [i, j]
dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + cost(i, k, j))Matrix chain multiplication
Multiplying a p × q matrix by a q × r matrix costs p·q·r scalar multiplications. Matrix multiplication is associative, so a chain A₁A₂…Aₙ can be parenthesized in many ways with very different costs. For A (10×30), B (30×5), C (5×60): (AB)C costs 10·30·5 + 10·5·60 = 4,500, while A(BC) costs 30·5·60 + 10·30·60 = 27,000.
- 1
State
Matrix
Aᵢhas dimensionsp[i-1] × p[i].m[i][j]= the minimum cost to compute the productAᵢ…Aⱼ. - 2
Last decision
The final multiplication splits the chain at some
k:(Aᵢ…Aₖ)(Aₖ₊₁…Aⱼ), ap[i-1] × p[k]matrix times ap[k] × p[j]matrix. - 3
Base case
m[i][i] = 0: a single matrix needs no multiplication. - 4
Order and answer
By increasing chain length; the answer is
m[1][n]. Store the bestkins[i][j]to print the parenthesization.
| m[i][j] (best k) | j = 1 | j = 2 | j = 3 | j = 4 |
|---|---|---|---|---|
| i = 1 | 0 | 24,000 (k=1) | 14,000 (k=1) | 26,000 (k=3) |
| i = 2 | 0 | 6,000 (k=2) | 12,000 (k=3) | |
| i = 3 | 0 | 9,000 (k=3) | ||
| i = 4 | 0 |
Burst balloons: think about the last action
Bursting balloon k earns nums[left] · nums[k] · nums[right], where left and right are its current neighbors, and then the neighbors become adjacent. If you think about which balloon to burst first, the two sides become entangled (their neighbors change). Think instead about which balloon in an interval is burst last: while it survives, it walls off the left part from the right part, so they are independent subproblems.
def max_coins(nums: list[int]) -> int:
a = [1] + nums + [1]
n = len(a)
dp = [[0] * n for _ in range(n)] # dp[i][j]: best for the open interval (i, j)
for length in range(2, n): # distance between the two walls
for i in range(0, n - length):
j = i + length
for k in range(i + 1, j): # k is the LAST balloon burst inside (i, j)
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + a[i] * a[k] * a[j])
return dp[0][n - 1]
print(max_coins([3, 1, 5, 8])) # 167Palindrome partitioning
To cut a string into palindromes with the fewest cuts, first build the interval table isPal[i][j], then run a 1D DP over prefixes. Doing both as one interval DP would cost O(n³); splitting them gives O(n²).
def min_cut(s: str) -> int:
n = len(s)
is_pal = [[False] * n for _ in range(n)]
cuts = [0] * n
for j in range(n):
cuts[j] = j # worst case: every char alone
for i in range(j + 1):
if s[i] == s[j] and (j - i < 2 or is_pal[i + 1][j - 1]):
is_pal[i][j] = True
cuts[j] = 0 if i == 0 else min(cuts[j], cuts[i - 1] + 1)
return cuts[-1]Other interval classics: longest palindromic subsequence (dp[i][j] = dp[i+1][j-1] + 2 when the ends match, else the max of dropping one end; it equals the LCS of the string and its reverse, see LCS & Edit Distance), minimum score triangulation of a polygon, optimal binary search trees and minimum cost to merge stones.
Bitmask DP
When the state must remember which of up to about 20 items have been used, encode the subset as the bits of an integer: bit i is 1 if item i is in the set. Testing, adding and removing items become single Bit Manipulation operations, and the state fits in an array index.
| Operation | Expression |
|---|---|
| Is item i in the set? | (mask >> i) & 1 |
| Add item i | mask | (1 << i) |
| Remove item i | mask & ~(1 << i) |
| Size of the set | popcount(mask) |
| Full set of n items | (1 << n) - 1 |
| Enumerate submasks of mask | for (s = mask; s > 0; s = (s - 1) & mask) |
Traveling salesman: Held-Karp
Visit every city exactly once and return to the start with minimum total distance. Trying all orders costs O(n!). The Held-Karp insight: once you know which cities are visited and where you are now, the order in which you visited them no longer matters for the rest of the tour.
- 1
State
dp[mask][v]= the minimum cost of a path that starts at city 0, visits exactly the cities inmask, and ends at cityv(withvinmask). - 2
Transition
Extend to an unvisited city
u:dp[mask | 1<<u][u] = min(…, dp[mask][v] + dist[v][u]). - 3
Base case
dp[{0}][0] = 0: we start at city 0 having visited only it. - 4
Order and answer
Masks in increasing numeric order (adding a bit always increases the number). The tour cost is
min over v of dp[full][v] + dist[v][0].
Brute force, n = 15
1.3 × 10¹²
15! orderings
Held-Karp, n = 15
7.4 × 10⁶
15² × 2¹⁵
Brute force, n = 20
2.4 × 10¹⁸
centuries of compute
Held-Karp, n = 20
4.2 × 10⁸
seconds in C++, but 20M states of memory
Assignment problems
Assign n workers to n jobs (one each) to minimize total cost. Process workers in order; the mask records which jobs are taken. Because exactly popcount(mask) workers have been assigned, the next worker's index is implied by the mask and need not be stored.
def min_assignment_cost(cost: list[list[int]]) -> int:
n = len(cost)
INF = float("inf")
dp = [INF] * (1 << n) # dp[mask] = best cost assigning jobs in mask
dp[0] = 0 # to workers 0 .. popcount(mask) - 1
for mask in range(1 << n):
if dp[mask] == INF:
continue
worker = bin(mask).count("1")
if worker == n:
continue
for job in range(n):
if not (mask >> job) & 1:
nxt = mask | (1 << job)
dp[nxt] = min(dp[nxt], dp[mask] + cost[worker][job])
return dp[(1 << n) - 1]
print(min_assignment_cost([[9, 2, 7, 8], [6, 4, 3, 7], [5, 8, 1, 8], [7, 6, 9, 4]])) # 13For large n, the Hungarian algorithm solves assignment in O(n³). Bitmask DP shines when the cost is not a simple sum of pairs, as in partition to K equal sum subsets, minimum XOR sum of two arrays, shortest path visiting all nodes (BFS over (mask, node) states) and find the shortest superstring (a TSP over string overlaps).
DP on trees
On a tree, each subtree is a natural subproblem, and subtrees of different children never overlap. Compute every node's DP values from its children's values with a post-order traversal (Tree Traversals, Depth-First Search). Each node is processed once, so tree DP is usually O(n).
House robber III
Houses form a binary tree and you cannot rob a node together with its parent. A single number per node is not enough, because the parent needs to know whether the child was robbed. Return a pair from each subtree instead.
def rob_tree(root) -> int:
def dfs(node) -> tuple[int, int]: # (best if robbed, best if skipped)
if node is None:
return 0, 0
l_rob, l_skip = dfs(node.left)
r_rob, r_skip = dfs(node.right)
robbed = node.val + l_skip + r_skip
skipped = max(l_rob, l_skip) + max(r_rob, r_skip)
return robbed, skipped
return max(dfs(root))
def diameter(root) -> int: # longest path, counted in edges
best = 0
def height(node) -> int: # nodes on the longest downward path
nonlocal best
if node is None:
return 0
lh, rh = height(node.left), height(node.right)
best = max(best, lh + rh) # path bending at this node
return 1 + max(lh, rh)
height(root)
return bestTree diameter follows the same shape: each node returns the height of its deepest downward path, and the longest path that bends at the node is the sum of its two deepest child heights. In a general (non-binary) tree, keep the top two child heights.
Rerooting: an answer for every root
Some problems ask for a value for every node as the root, such as the sum of distances from each node to all others. Running a DFS from each root costs O(n²). Rerooting does it in O(n) with two passes:
- 1
Pass 1 (post-order)
Root the tree at node 0. Compute
size[v](nodes in v's subtree) anddown[v](sum of distances from v to its subtree nodes):down[v] = Σ (down[c] + size[c])over children c. Thenans[0] = down[0]. - 2
Pass 2 (pre-order)
Move the root from parent
pto childv. Thesize[v]nodes in v's subtree each get 1 closer; the othern − size[v]nodes each get 1 farther.
| node | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| size (rooted at 0) | 6 | 1 | 4 | 1 | 1 | 1 |
| ans | 8 | 12 | 6 | 10 | 10 | 10 |
State-machine DP
Some problems move through a small set of modes over time, with rules about which mode can follow which. Make the mode part of the state: dp[i][mode]. The stock trading problems are the canonical example.
| Mode on day i | Meaning | Can come from |
|---|---|---|
| hold | Own one share at the end of the day | hold (do nothing) or rest (buy today) |
| sold | Sold today, so tomorrow is a cooldown | hold (sell today) |
| rest | Own nothing and free to buy tomorrow | rest (do nothing) or sold (cooldown ends) |
| day | price | hold | sold | rest |
|---|---|---|---|---|
| 0 | 1 | −1 | −∞ | 0 |
| 1 | 2 | −1 | 1 | 0 |
| 2 | 3 | −1 | 2 | 1 |
| 3 | 0 | 1 | −1 | 2 |
| 4 | 2 | 1 | 3 | 2 |
def max_profit_cooldown(prices: list[int]) -> int:
hold, sold, rest = float("-inf"), float("-inf"), 0
for p in prices:
hold, sold, rest = max(hold, rest - p), hold + p, max(rest, sold)
return max(sold, rest)
def max_profit_fee(prices: list[int], fee: int) -> int:
cash, hold = 0, float("-inf") # not holding / holding a share
for p in prices:
cash, hold = max(cash, hold + p - fee), max(hold, cash - p)
return cash
print(max_profit_cooldown([1, 2, 3, 0, 2])) # 3
print(max_profit_fee([1, 3, 2, 8, 4, 9], 2)) # 8| Problem | Modes | Notes |
|---|---|---|
| Buy and sell once | hold, cash | hold = max(hold, −p) (can only buy from zero profit) |
| Unlimited transactions | hold, cash | Equivalent to summing every positive day-to-day rise |
| At most 2 transactions | buy1, sell1, buy2, sell2 | Four running maxima |
| At most k transactions | 2k modes | O(n·k); if k ≥ n/2 it is the unlimited case |
| With cooldown | hold, sold, rest | Shown above |
| With transaction fee | hold, cash | Subtract the fee once per sale |
Digit DP
Digit DP counts integers in a range [0, N] whose digits satisfy some property (digit sum equals S, no repeated digits, no two adjacent equal digits). Build the number one digit at a time from the most significant position. The crucial flag is tight: whether the prefix so far equals N's prefix, in which case the next digit is capped at N's digit; otherwise any digit 0 to 9 is allowed. Counts on [L, R] come from f(R) − f(L − 1).
from functools import cache
def count_digit_sum(N: int, S: int) -> int:
digits = list(map(int, str(N)))
@cache
def go(pos: int, total: int, tight: bool) -> int:
if total > S:
return 0 # prune: sums only grow
if pos == len(digits):
return 1 if total == S else 0
limit = digits[pos] if tight else 9
return sum(go(pos + 1, total + d, tight and d == limit)
for d in range(limit + 1))
return go(0, 0, True)
print(count_digit_sum(100, 5)) # 6: 5, 14, 23, 32, 41, 50- States: positions (about 19 for 64-bit numbers) × tight (2) × the extra property (digit sum, last digit, a mask of used digits…).
- Add a started flag when leading zeros would break the property (for example "all digits distinct", where 007 must not count 0 twice).
- Only non-tight states are truly shared; the tight path is a single chain, which is why memoizing on
tightcosts little.
Speeding up a correct DP
Sometimes the state space is right but the transitions are too expensive. These classic optimizations reduce the cost per transition by exploiting structure in the recurrence. They appear in competitive programming far more than in interviews, but recognizing them is valuable.
| Technique | Applies when | Speedup | Example |
|---|---|---|---|
| Monotonic queue | dp[i] = max/min of dp[j] over a sliding window of j, plus a term in i | O(n·k) → O(n) | Constrained subsequence sum, jump game VI, bounded knapsack |
| Convex hull trick | dp[i] = min over j of (m_j·x_i + b_j): each j is a line evaluated at x_i | O(n²) → O(n) with monotone slopes, O(n log n) with a Li Chao tree | Partitioning arrays with quadratic costs, AtCoder DP contest "Frog 3" |
| Knuth optimization | Interval DP whose optimal split satisfies opt[i][j−1] ≤ opt[i][j] ≤ opt[i+1][j] (quadrangle inequality) | O(n³) → O(n²) | Optimal binary search trees, merging adjacent piles |
| Divide and conquer optimization | Layered DP dp[k][i] = min over j of dp[k−1][j] + C(j, i) with monotone optimal j | O(k·n²) → O(k·n log n) | Splitting an array into k groups with convex costs |
| Bitset | Boolean DP with shift-and-OR transitions | ÷ 64 | Subset sum, partition |
The monotonic queue is the one most likely to come up in an interview. If dp[i] = nums[i] + max(dp[i−k..i−1]), keep a deque of indices whose dp values are decreasing; the front is always the window maximum. It is the same idea as the sliding window maximum (Sliding Window, Monotonic Stack & Queue).
Complexity
| Problem | Time | Space | Pattern |
|---|---|---|---|
| Matrix chain multiplication | O(n³) | O(n²) | Interval |
| Burst balloons | O(n³) | O(n²) | Interval (last action) |
| Palindrome partitioning II | O(n²) | O(n²) | Interval table + 1D prefix DP |
| Traveling salesman (Held-Karp) | O(n²·2ⁿ) | O(n·2ⁿ) | Bitmask |
| Assignment (bitmask) | O(n·2ⁿ) | O(2ⁿ) | Bitmask |
| House robber III, tree diameter | O(n) | O(h) | Tree (h = height, for recursion) |
| Sum of distances (rerooting) | O(n) | O(n) | Tree, two passes |
| Stock with cooldown / fee | O(n) | O(1) | State machine |
| Digit DP (digit sum) | O(d·S·10) | O(d·S) | Digit, d = number of digits |
Every row follows the same rule: number of states × work per transition.
Implementation
Fills m[i][j] by increasing chain length, records the best split s[i][j], and rebuilds the optimal parenthesization.
def matrix_chain(p: list[int]) -> tuple[int, str]:
n = len(p) - 1 # matrix i (1-based) is p[i-1] x p[i]
m = [[0] * (n + 1) for _ in range(n + 1)]
s = [[0] * (n + 1) for _ in range(n + 1)]
for length in range(2, n + 1): # chain length
for i in range(1, n - length + 2):
j = i + length - 1
m[i][j] = float("inf")
for k in range(i, j): # last multiplication splits at k
cost = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]
if cost < m[i][j]:
m[i][j], s[i][j] = cost, k
def paren(i: int, j: int) -> str:
if i == j:
return chr(ord("A") + i - 1)
return "(" + paren(i, s[i][j]) + paren(s[i][j] + 1, j) + ")"
return m[1][n], paren(1, n)
print(matrix_chain([40, 20, 30, 10, 30])) # (26000, '((A(BC))D)')Key takeaways
- Advanced DP is mostly about choosing the state: a range, a subset bitmask, a tree node with flags, a mode, or a digit position with a tight flag.
- Interval DP fills by increasing length and tries every split or every last action; it is typically O(n³).
- Bitmask DP handles "which items are used" for n up to about 20; Held-Karp solves TSP in O(n²·2ⁿ) instead of O(n!).
- Tree DP runs in post-order and returns several values per node; rerooting gets an answer for every root in O(n).
- State-machine DP turns rules like cooldowns and fees into a few variables updated per step; digit DP counts numbers in a range with a tight flag.
Common pitfalls
- Filling an interval table row by row instead of by increasing length, so sub-intervals are read before they are computed.
- Choosing the first action in burst balloons, which makes subproblems depend on each other.
- Using bitmask DP for n = 30 or more: 2³⁰ states with n values each will not fit in memory or time.
- Returning a single number from a tree DP when the parent needs to know the child's choice (robbed or not).
- Updating state-machine variables in place so that today's value is used where yesterday's was required.
Interview tips
- Map the problem to a pattern by its signal: small n → bitmask; operations on a contiguous range → interval; a tree → post-order DP; modes over time → state machine.
- For tree DP, say what each node returns ("a pair: best if I take this node, best if I skip it") before writing code.
- Draw the state diagram for stock-style problems and derive one
maxper arrow. - Quote complexity from the state count and mention optimizations (monotonic queue, Knuth) only if asked about speeding things up.
Real-world applications
- Compilers and query planners choosing multiplication or join orders (matrix chain, join ordering in databases).
- Vehicle routing, drilling and PCB manufacturing using exact TSP on small subproblems.
- RNA secondary structure prediction (Nussinov and Zuker algorithms are interval DPs).
- Network design and facility placement on tree-shaped networks via tree DP.
- Trading strategy backtests with transaction costs and holding constraints (state-machine DP).
Practice problems
Test yourself
In burst balloons, why does the recurrence pick the balloon burst last in an interval?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.