Dynamic Programming
Remember what you've already solved — the idea that turns exponential recursions into polynomial tables.
- turn an inductive definition into a memoised or bottom-up solution
- fill LCS, common-subword, edit-distance and grid-path tables by hand
- state the cost of a DP as (#subproblems × work per subproblem)
- explain the matrix-chain and knapsack recurrences
The problem with plain recursion
Fibonacci numbers are defined inductively: F(0) = 0, F(1) = 1, F(n) = F(n−1) + F(n−2). Translating that definition straight into code is natural — and terrible.
fib(n) calls fib(n−2) once directly and again inside fib(n−1). The same subproblems are solved over and over, so the number of calls grows like 1.618ⁿ. But there are only n + 1 distinct subproblems! If we remember each answer after computing it, the work collapses to O(n).
Memoisation (top-down)
Keep a table (dictionary). Before computing fib(k), look it up; after computing, store it. The recursion is unchanged, but each value is computed once.
Dynamic programming (bottom-up)
Skip recursion: fill the table in an order where every dependency is already computed — here 0, 1, 2, …, n. Often only the last few entries are needed, so memory can drop too.
- Find an inductive definition of the answer in terms of smaller subproblems.
- Notice that subproblems overlap (the same ones are needed many times).
- Pick an order in which dependencies are computed first — or memoise the recursion.
- Read the answer from the table. Cost = (number of subproblems) × (work per subproblem).
Why is naive recursive Fibonacci exponential but memoised Fibonacci linear?
What does this print?
memo = {}
def f(n):
if n in memo:
return memo[n]
memo[n] = n if n < 2 else f(n - 1) + f(n - 2)
return memo[n]
f(6)
print(len(memo), memo[6])Counting paths on a grid
A robot moves on an R × C grid, one step right or down. Some cells are blocked. How many different routes lead from the top-left to the bottom-right?
Inductive definition. Let paths(i, j) be the number of routes to cell (i, j). A route must arrive from the cell above or the cell to the left, so paths(i, j) = paths(i−1, j) + paths(i, j−1) — or 0 if (i, j) is blocked. Fill the table row by row.
Time and space are both O(R·C): one table entry, each computed with O(1) work.
Number of right/down routes in an open 3×3 grid?
R, C = 3, 3
P = [[1] * C for _ in range(R)]
for i in range(1, R):
for j in range(1, C):
P[i][j] = P[i - 1][j] + P[i][j - 1]
print(P[-1][-1])In grid-path counting, which order fills the table so every dependency is ready?
Longest common subsequence (LCS)
A subsequence keeps letters in order but may skip some: "sct" is a subsequence of "secret". Given two strings, find the length of their longest common subsequence — used in diff tools, DNA comparison and plagiarism checks.
Inductive definition. Let L(i, j) be the LCS length of the suffixes a[i:] and b[j:]. If a[i] == b[j], we can match them: L(i, j) = 1 + L(i+1, j+1). Otherwise one of them is unmatched: L(i, j) = max(L(i+1, j), L(i, j+1)). The base case is an empty suffix: 0.
(m+1)(n+1) cells, each O(1) ⇒ O(mn) time and space. The naive recursion explores 2^(m+n) paths.
Longest common substring (contiguous)
If the matched letters must be consecutive (a common subword), the recurrence changes: LCW(i, j) = 1 + LCW(i+1, j+1) if a[i] == b[j], otherwise 0 (the run is broken). The answer is the maximum entry in the table, not the corner.
What does this print? (type the exact output)
def lcs(a, b):
m, n = len(a), len(b)
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
L[i][j] = 1 + L[i + 1][j + 1] if a[i] == b[j] else max(L[i + 1][j], L[i][j + 1])
return L[0][0]
print(lcs("ABCBDAB", "BDCABA"))a = 'abc', b = 'acb'. What is the LCS length?
Edit distance
How many single-character edits turn one word into another? Allowed edits: insert a letter, delete a letter, substitute one letter. ED("bisect", "secret") is the minimum number of operations — the idea behind spell-checkers and DNA alignment.
Inductive definition. Let E(i, j) be the distance between the suffixes a[i:] and b[j:]. If one is empty, we must insert or delete the rest: E(m, j) = n − j and E(i, n) = m − i. Otherwise: - if a[i] == b[j], no edit is needed: E(i, j) = E(i+1, j+1); - else take 1 + min(E(i+1, j) [delete], E(i, j+1) [insert], E(i+1, j+1) [substitute]).
What does this print?
def ed(a, b):
m, n = len(a), len(b)
E = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1): E[i][n] = m - i
for j in range(n + 1): E[m][j] = n - j
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
E[i][j] = E[i+1][j+1] if a[i] == b[j] else 1 + min(E[i+1][j], E[i][j+1], E[i+1][j+1])
return E[0][0]
print(ed("cat", "cut"), ed("cat", "cart"), ed("abc", "xyz"))For strings of lengths m and n, the edit-distance table has how many cells?
Matrix chain multiplication
Multiplying a p×q matrix by a q×r matrix costs p·q·r scalar multiplications. Matrix multiplication is associative, so (AB)C and A(BC) give the same product — but the costs can differ wildly. Given a chain M₁M₂…Mₙ, find the cheapest way to parenthesise it.
A is 10×100, B is 100×5, C is 5×50. (AB)C costs 10·100·5 + 10·5·50 = 5000 + 2500 = 7500. A(BC) costs 100·5·50 + 10·100·50 = 25000 + 50000 = 75000. Ten times worse!
Inductive definition. Let C(i, j) be the cheapest cost of multiplying Mᵢ … Mⱼ. Choose where to make the last split k, with i ≤ k < j: the cost is the left part + the right part + the final multiplication of the two results:
C(i, j) = min over k of [ C(i, k) + C(k+1, j) + rᵢ · c_k · c_j ], C(i, i) = 0
Here matrix Mᵢ has dimensions rᵢ × cᵢ. We fill the table in order of increasing chain length: all intervals of length 2, then 3, and so on. There are O(n²) subproblems with O(n) choices each: O(n³) time.
Why can't we just always multiply left to right?
A is 2×3, B is 3×4. How many scalar multiplications does AB take?
Choices with a budget: 0/1 knapsack
You have a bag that holds weight W and items with weights and values. Take each item or leave it; maximise total value. Greedy by value-per-weight fails here, but DP works. Let K(i, w) be the best value using the first i items with capacity w:
K(i, w) = max( K(i−1, w), v_i + K(i−1, w − w_i) ) (second option only if w_i ≤ w)
The table has n × W cells. That is fast if W is small, but W is a number, and its input size is only log W bits — so the running time is exponential in the size of the input. Knapsack is NP-hard.
Minimum number of coins {1, 3, 4} to make 6?
coins = [1, 3, 4]
best = [0] + [float("inf")] * 6
for amount in range(1, 7):
for c in coins:
if c <= amount:
best[amount] = min(best[amount], best[amount - c] + 1)
print(best[6])Chapter challenge — Week 9
The two requirements for dynamic programming to help are…
What does this print? (type the exact output)
def paths(r, c):
P = [[1] * c for _ in range(r)]
for i in range(1, r):
for j in range(1, c):
P[i][j] = P[i-1][j] + P[i][j-1]
return P[-1][-1]
print(paths(4, 4))Filling the LCS table for strings of length 300 and 400 takes about…
Designing a DP solution.
What is the edit distance between 'ab' and 'ba'?
What does this print? (type the exact output)
a, b = "abcd", "acbd"
m, n = len(a), len(b)
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
L[i][j] = 1 + L[i+1][j+1] if a[i] == b[j] else max(L[i+1][j], L[i][j+1])
print(L[0][0])Which statements about DP are true?
Why does greedy fail for coin change with coins {1, 3, 4} and amount 6?
Practice on LeetCode
Dynamic programming: sequences, grids, knapsack, strings and intervals.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Fibonacci Number ↗ | Easy | memoise or fill a table | |
| Climbing Stairs ↗ | Easy | the same recurrence | |
| House Robber ↗ | Medium | choose-or-skip DP | |
| Unique Paths ↗ | Medium | grid paths | |
| Unique Paths II ↗ | Medium | grid paths with blocked cells | |
| Minimum Path Sum ↗ | Medium | grid DP with min | |
| Coin Change ↗ | Medium | where greedy fails and DP works | |
| Partition Equal Subset Sum ↗ | Medium | 0/1 knapsack | |
| Target Sum ↗ | Medium | subset-sum style DP | |
| Longest Increasing Subsequence ↗ | Medium | O(n²) DP, then the O(n log n) idea | |
| Longest Common Subsequence ↗ | Medium | the LCS table from this chapter | |
| Maximum Length of Repeated Subarray ↗ | Medium | longest common subword (diagonal runs) | |
| Edit Distance ↗ | Medium | the edit-distance table | |
| Delete Operation for Two Strings ↗ | Medium | LCS in disguise | |
| Burst Balloons ↗ | Hard | interval DP, like matrix-chain |
Key takeaways
- Naive recursion re-solves the same subproblems; DP solves each once and stores the answers — top-down (memoisation) or bottom-up (table).
- The recipe: inductive definition → overlapping subproblems → fill order → read the answer. Cost = number of subproblems × work each.
- LCS / longest common subword / edit distance fill an m×n table in O(mn).
- Matrix chain: O(n²) subproblems with O(n) splits each ⇒ O(n³). Knapsack: O(nW), pseudo-polynomial.
- Where greedy fails (arbitrary coin change), DP still finds the optimum.