Dynamic Programming Patterns
The DP recipe, the classic templates, and how to recognize a DP problem in the wild.
Dynamic programming solves a problem by combining answers to smaller versions of the same problem, computing each smaller answer once. It applies when subproblems overlap — plain recursion would solve the same ones again and again — and when the best overall answer is built from best answers to the parts.
Every DP comes down to three decisions: the state (what dp[i] means, said in words), the transition (how one state is computed from smaller ones), and the order (so every dependency is ready first). Get the state right and the code is usually a dozen lines.
fib(30) makes 2,692,537 calls. A table keyed by the state solves each of its 31 states once, in an order where the inputs are already filled.The DP recipe
- 0. Brute force first
- write the plain recursion, then spot repeated arguments — those are the states to cache
- 1. State
- What does
dp[...]mean? The fewest indices that pin a subproblem. - 2. Transition
- Express
dp[state]from smaller states — the recurrence over choices. - 3. Base cases
- Smallest states set directly (empty prefix = 0, dp[0] = 1, …).
- 4. Order
- Bottom-up table (iterate so deps come first) or top-down memo (recurse + cache).
- 5. Answer
- Which state holds the result — often
dp[n]ordp[n][m]. - 6. Check by hand
- fill the table for a tiny input on paper before trusting the code
Classic patterns — state · recurrence · cost
- Kadane (max subarray)
best_here = max(x, best_here + x)· track global max ·O(n)- 0/1 Knapsack
dp[i][w] = max(skip, take + dp[i-1][w-wi])·O(n·W)- Coin change (min coins)
dp[a] = min(dp[a], dp[a-coin] + 1)·O(n·A)- Longest increasing subseq.
dp[i] = 1 + max(dp[j] : a[j]<a[i])=O(n²), or tails/patienceO(n log n)- Longest common subseq.
- match →
dp[i-1][j-1]+1, elsemax(up, left)·O(n·m) - Edit distance
- match → diagonal, else
1 + min(ins, del, replace)·O(n·m)
1-D and grid templates
- Climbing stairs / Fibonacci
dp[i] = dp[i-1] + dp[i-2]·O(n)time,O(1)space with two variables- House robber
dp[i] = max(dp[i-1], dp[i-2] + nums[i])— skip this house or take it- Max product subarray
- Kadane tracking both max and min — a negative number swaps them
- Decode ways
- add
dp[i-1]if one digit is valid,dp[i-2]if the two digits form 10–26 - Unique grid paths
dp[r][c] = dp[r-1][c] + dp[r][c-1]·O(R·C), one row of memory- Minimum path sum
dp[r][c] = grid[r][c] + min(up, left); the first row and column are prefix sums- Stock with cooldown / fee
- a state machine per day —
hold,sold,rest— each from yesterday’s three - Word break
dp[i] = any(dp[j] and s[j:i] in words)·O(n²)substring checks
Knapsack family & counting
- 0/1 knapsack in 1-D
- loop capacity downward, so each item is used at most once
- Unbounded knapsack
- loop capacity upward, so an item can be reused within the same pass
- Subset sum / partition
dp[s] = dp[s] or dp[s-x]·O(n·S); partition targets half the total- Coin change (count ways)
ways[a] += ways[a-c]; coins in the outer loop count combinations, not orderings- Counts get huge
- take results modulo
10⁹ + 7when asked — after every addition, not at the end
Strings, intervals & trees
- Longest palindromic subseq.
- ends match →
dp[i+1][j-1] + 2, elsemax(dp[i+1][j], dp[i][j-1])·O(n²) - Interval DP
dp[i][j] = min over k of dp[i][k] + dp[k+1][j] + cost·O(n³), e.g. matrix chain- Interval fill order
- iterate by interval length, short to long, so both halves are ready
- DP on trees
- post-order DFS returning a small tuple per node, e.g. (best with node, best without)
- Digit DP
- count numbers ≤ N with a property: state = (position, still tight to N, extra), memoized
Optimizations
- Rolling array
- Only recent rows matter → drop a dimension,
O(n·m)space becomesO(min(n,m)) - Memo vs tabulation
- Top-down recursion + cache is easy to write; bottom-up avoids stack + is often faster
- Bitmask DP
- State is a subset →
dp[mask]:O(2ⁿ · n)for assignment,O(2ⁿ · n²)for TSP - Deque / monotonic
- Sliding-window max in transitions → amortized
O(1)(also convex-hull trick)
Spotting a DP
- Overlapping subproblems
- The same smaller problem recurs many times — cache it
- Optimal substructure
- The best overall is built from best answers to subproblems
- Count / min / max / feasible
- Asking how many, best, or possible over a sequence of choices
- Exponential brute force
- Recursion with repeated states → memoize, then tabulate
- Greedy fails
- coins 1, 3, 4 for amount 6: greedy takes 4+1+1, DP finds 3+3 — hunt for a counterexample
- Constraints as hints
- n ≤ 20 hints bitmask; n ≤ 1,000 hints
O(n²); small capacity or sum hints knapsack
Pitfalls & debugging
- Size n + 1
- index
dpby prefix length sodp[0]is the empty case — fewer off-by-ones - Infinity for min
- start a min table at infinity and report “impossible” if the answer stays there
- Recursion depth
- Python stops at about 1,000 frames by default — go bottom-up for long inputs
- lru_cache arguments
- must be hashable: pass tuples or indices, never lists
- Fill order
- compute every state before anything that reads it — draw the dependency arrows
- Rebuilding the answer
- store the choice made at each state, or walk the table backward, to output the solution
Worked example: 0/1 knapsack, where greedy loses
Four items as (weight, value): (1, 1), (3, 4), (4, 5), (5, 7). The bag holds 7. Greedy by value per unit of weight takes (5, 7) first, the best ratio at 1.4, then (1, 1): total 8. DP finds 9.
State: dp[c] = best value within capacity c using the items seen so far. One pass per item, capacity looping down from 7 to the item’s weight:
c: 0 1 2 3 4 5 6 7
start 0 0 0 0 0 0 0 0
after (1, 1) 0 1 1 1 1 1 1 1
after (3, 4) 0 1 1 4 5 5 5 5
after (4, 5) 0 1 1 4 5 6 6 9
after (5, 7) 0 1 1 4 5 7 8 9- Item (4, 5) lifts
dp[7]from 5 to 9: its value plusdp[3] = 4, the best use of the 3 units left. - Item (5, 7) cannot beat that:
7 + dp[2] = 8. - Loop upward instead and item (1, 1) sets
dp[2] = 2by using itself twice. The final cell is still 9 here by luck; the table is wrong. - To list the items, keep the 2-D table
dp[i][c]and walk back fromdp[4][7]: wherever a cell differs from the one above, itemiwas taken. That gives (4, 5) and (3, 4).
Cost: 4 items × 8 capacities = 32 cell updates. That is O(n·W), fast only while W stays small.
Recipes
Coin change, table filled in (coins 1, 2, 5; amount 11)
dp[a] = fewest coins that sum to a; dp[0] = 0, every other entry starts at infinity
dp[a] = min(dp[a], dp[a - c] + 1) for each coin c <= a
a: 0 1 2 3 4 5 6 7 8 9 10 11
dp[a]: 0 1 1 2 2 1 2 2 3 3 2 3
answer: dp[11] = 3 (5 + 5 + 1)Each cell asks “which coin did I use last?” and looks up the best way to make the rest. An entry still at infinity at the end means the amount cannot be made.
Longest common subsequence of "ABCDE" and "ACE"
"" A C E
"" 0 0 0 0
A 0 1 1 1
B 0 1 1 1
C 0 1 2 2
D 0 1 2 2
E 0 1 2 3
letters match -> dp[i][j] = dp[i-1][j-1] + 1 (diagonal)
otherwise -> dp[i][j] = max(dp[i-1][j], dp[i][j-1])
answer dp[5][3] = 3: "ACE"The extra empty row and column hold the base case (an empty string shares nothing), which removes every special case at the edges. Walk back from the bottom-right corner along the diagonals to recover the subsequence.
House robber: from recursion to O(1) space
from functools import lru_cache
# top-down: best(i) = max(skip house i, rob it + best(i - 2))
def rob(nums):
@lru_cache(maxsize=None)
def best(i):
if i < 0:
return 0
return max(best(i - 1), best(i - 2) + nums[i])
return best(len(nums) - 1)
# bottom-up with two variables: O(n) time, O(1) space
def rob_iter(nums):
prev2 = prev1 = 0
for x in nums:
prev2, prev1 = prev1, max(prev1, prev2 + x)
return prev1
rob_iter([2, 7, 9, 3, 1]) # 12 = 2 + 9 + 1Same recurrence twice: the iterative version keeps only the two states it reads, and it avoids Python’s recursion limit on long inputs.
Counting ways: why the loop order matters (coins 1, 2; amount 3)
# coins outer -> combinations: {1,1,1}, {1,2} ways[3] = 2
ways = [1, 0, 0, 0]
for c in (1, 2):
for a in range(c, 4):
ways[a] += ways[a - c]
# amounts outer -> orderings: 1+1+1, 1+2, 2+1 ways[3] = 3
ways = [1, 0, 0, 0]
for a in range(1, 4):
for c in (1, 2):
if c <= a:
ways[a] += ways[a - c]With coins in the outer loop, coins are added in a fixed order, so 1+2 and 2+1 count once. Swap the loops and every ordering counts — which is the climbing-stairs answer.
Edit distance: "kitten" to "sitting"
dp[i][j] = edits to turn the first i letters of a into the first j letters of b
dp[i][0] = i (delete everything), dp[0][j] = j (insert everything)
dp[i][j] = dp[i-1][j-1] if a[i-1] == b[j-1]
= 1 + min(dp[i-1][j], # delete from a
dp[i][j-1], # insert into a
dp[i-1][j-1]) # replace
kitten -> sitting = 3: k->s, e->i, then insert gThe table is (n+1) × (m+1), filled row by row, and only the previous row is ever read — so two rows of memory are enough.
When to use it, and when not
Use DP when the brute force is a tree of choices and the same sub-question keeps coming back: counting paths, the cheapest way to finish, whether a target is reachable. The table must fit in memory, and a 10,000 × 10,000 table is already 100 million cells.
- Greedy instead when you can prove the local choice is safe: interval scheduling by earliest end, Huffman coding, minimum spanning trees. Simpler, and usually
O(n log n). - Graph search instead when states can lead back to themselves. DP needs an order where every input is ready, so a grid you can walk in all four directions is a shortest-path problem for BFS or Dijkstra.
- Backtracking instead when you must list every solution rather than count them. The output itself is exponential, so no table helps.
- Meet-in-the-middle instead when one dimension is huge. Knapsack with capacity 10⁹ is out of reach for an
O(n·W)table, but with n ≤ 40 you can enumerate the 2²⁰ subsets of each half, sort one side and binary-search it.
Trade-offs and limits
DP trades memory for time. The number of states is the real cost, and a pseudo-polynomial bound like O(n·W) grows with the value of W, not the number of digits in it.
| Style | Gives you | Costs you |
|---|---|---|
| Top-down memo | Only reachable states computed; code mirrors the recurrence | Call overhead, the recursion limit, hashing every key |
| Bottom-up table | No recursion, tight loops, easy to roll rows | Fills every state, reachable or not; you must work out the order |
| Rolling rows | One dimension less memory | The choices are gone, so rebuilding the solution needs extra work (Hirschberg’s method for LCS) |
| Bitmask state | Exact answers over subsets | 2ⁿ states: n = 20 is about a million, n = 30 about a billion |
Common mistakes
- A state that forgets something it needs. For LIS, “best length within the first i items” cannot be extended, because you do not know the last value. “Longest run ending at i” can. If the transition needs a fact, the fact belongs in the state.
- Reading the answer from the wrong cell. With an “ending at i” state the answer is
max(dp), not the last cell. For [3, 1, 2, 0] the LIS table is [1, 1, 2, 1]: the last cell says 1, the answer is 2. - A cache that outlives its input. A module-level
@lru_cachefunction that reads a global list keeps its old answers when the list changes, so the second test case gets the first one’s results. Define the cached function inside the solver, or callcache_clear(). - Caching on a slice.
solve(tuple(nums[i:]))copies and hashes the rest of the input for every state, which isO(n²)time and memory spent on keys alone. Pass the indexi. - Forcing DP onto a cycle. If state A depends on B and B on A, there is no fill order, and memoized recursion loops until it hits the recursion limit. That is a shortest-path problem.
Check yourself
Coins 1, 3 and 4, amount 6. What does the min-coins table dp[0..6] hold?
[0, 1, 2, 1, 1, 2, 2], so the answer is 2 coins (3 + 3). Greedy would spend 3.
One item, weight 2 and value 3, capacity 6. With the 1-D table looping capacity upward, what is dp[6]?
9: the item is reused three times, which is the unbounded-knapsack answer. Looping downward gives the correct 0/1 answer, 3.
With dp[i] = LIS ending at i, what is the table for [10, 9, 2, 5, 3, 7, 101, 18]?
[1, 1, 1, 2, 2, 3, 4, 4]. The answer is the maximum, 4, for example 2, 3, 7, 18.
What is the edit distance from “sunday” to “saturday”?
3: insert a, insert t, and replace n with r.
Questions about Dynamic Programming Patterns Cheat Sheet
How do I recognize a dynamic programming problem?
Look for two properties. First, overlapping subproblems: if you write the natural recursive solution, it calls itself with the same arguments many times. Second, optimal substructure: the best answer for the whole is assembled from the best answers for smaller parts. The wording helps too: questions asking for the number of ways, the minimum or maximum cost, or whether something is possible, over a sequence of choices, are usually DP. Constraints are another clue, since an n around 1,000 often means an O(n squared) table, while an n around 20 suggests a bitmask over subsets.
What is the difference between memoization and tabulation?
They are the two ways to implement the same recurrence. Memoization is top-down: you write the recursive function and cache each result, so only the states actually reached get computed, and the code mirrors the recurrence closely. Tabulation is bottom-up: you allocate a table and fill it in an order where every dependency is already computed, which avoids recursion overhead and stack limits and makes memory tricks such as keeping one row easy. Start with memoization to get correctness, and convert to tabulation when you need speed, less memory or very large inputs.
What is the difference between dynamic programming and a greedy algorithm?
A greedy algorithm makes the locally best choice at each step and never revisits it, which is fast but only correct when a proof shows the local choice is always safe, as in interval scheduling or Dijkstra. Dynamic programming considers every choice at each step and keeps the best combination, so it stays correct where greedy fails. Making change for 6 with coins 1, 3 and 4 shows the difference: greedy takes 4, 1 and 1 for three coins, while DP finds 3 and 3. When you cannot prove the greedy choice, try DP.
What is the difference between dynamic programming and divide and conquer?
Both split a problem into smaller subproblems and combine their answers. In divide and conquer, such as merge sort or quicksort, the subproblems are independent and do not overlap, so each is solved exactly once and caching would gain nothing. Dynamic programming is for the case where subproblems do overlap, as in Fibonacci, where the same value is needed by many branches. Storing each answer the first time it is computed turns an exponential recursion into a polynomial one. If you see the same arguments recurring in a recursion tree, it is a DP problem.