Dynamic Programming
Solve each subproblem once, then build the answer from small to large.
There are 1,346,269 ways to climb a staircase of 30 steps if you take one or two steps at a time. Listing them would take more than a million steps; a row of 31 numbers, each the sum of the two before it, gives the count in 29 additions. Solving each smaller question once and reusing the answer is the whole idea of dynamic programming.
What you’ll learn
- Explain why naive recursion recomputes overlapping subproblems, and how memoization (top-down) and tabulation (bottom-up) solve each one only once.
- Fill small DP tables by hand (stairs, grid walks, longest common subsequence) and trace back an optimal solution.
- Apply the recipe (state, transition, base cases, order, answer) and estimate the cost as the number of states times the work per state.
- Recognize problems that call for dynamic programming, and tell them apart from greedy and divide-and-conquer problems.
The same question, again and again
Take the Fibonacci numbers: , and . The definition is already a recursive program, and a correct one. It is also hopelessly slow.
Look at what it asks. To compute it computes and , but computing computes again, and both of them compute . The recursion tree has a node for every call, and the same small questions appear in it over and over.
The naive recursion returns fib(7) = 13. Counting every call, base cases included, how many calls does it make?
Show the answer
41
Let be the number of calls for fib(): and , which gives . In fact , so the calls grow like the Fibonacci numbers themselves, by a factor of about 1.618 per step: fib(40) takes 331,160,281 calls.
Bottom-up: fill a table
How many ways can you climb stairs if each move goes up one stair or two? Think about the last move. It started on stair (a single step) or on stair (a double step), and no climb is in both groups, so
The base cases are (the empty climb) and . Instead of recursing down from , fill the table up from 0, left to right, so that the two cells a new cell reads are always ready. Filling a table in such an order is called tabulation, or bottom-up DP; memoized recursion is top-down DP.
from functools import cache
@cache # top-down: recursion + a memo table
def ways_top(n):
if n <= 1:
return 1
return ways_top(n - 1) + ways_top(n - 2)
def ways_bottom(n): # bottom-up: fill the table left to right
ways = [1] * (n + 1) # ways[0] = ways[1] = 1
for i in range(2, n + 1):
ways[i] = ways[i - 1] + ways[i - 2]
return ways[n]
print(ways_top(30), ways_bottom(30)) # 1346269 1346269Both versions compute each once, so both take additions instead of exponentially many calls. @cache (Python 3.9 and later) stores every result, keyed by the argument, and returns the stored value on a repeat call.
Think first Why is rather than 0? There are no stairs to climb.
Because the recurrence sorts climbs by their last move. A climb of 2 stairs is a single step after a climb of 1, or a double step after a climb of 0. Setting counts "one double step from the ground" exactly once, so (1+1 and 2). With 0, the double step would never be counted. Choosing base cases that make the recurrence count correctly at the edges is part of designing a DP.
A choice at every cell
A table can also optimize. Walk from the top-left cell of the grid below to the bottom-right one, moving only right or down, and pay the number in every cell you enter, the first and last included. What is the cheapest walk?
There are walks here (choose which 3 of the 7 moves go down), and on a grid there are . But every walk enters cell from above or from the left, so the cheapest walk to it costs
with only one option on the top row and the left column. That is one value per cell: 20 here, 400 on the big grid.
| row | col 0 | col 1 | col 2 | col 3 | col 4 |
|---|---|---|---|---|---|
| 0 | 3 | 7 | 2 | 1 | 3 |
| 1 | 4 | 8 | 5 | 1 | 6 |
| 2 | 5 | 7 | 2 | 2 | 2 |
| 3 | 4 | 4 | 1 | 6 | 6 |
Think first What does the greedy walker pay in total?
. Its cheap-looking first steps lead into an expensive corridor. The cheapest walk pays the 7 early to reach the cheap middle of the grid: .
Two strings, one table
A subsequence keeps some letters of a string in their original order: ATON and CTON are subsequences of both CARTOON and ACTION. The length of a longest common subsequence (LCS) measures how much two strings share, and the same idea compares two versions of a file, two DNA sequences, or a typo with a dictionary word.
Let be the LCS length of the first letters of and the first letters of . Look at their last letters, and :
In the CARTOON / ACTION table, . What does that cell say?
- CARTOON and ACTION have exactly 2 letters in common
- A longest common subsequence of CART and ACT has length 2
- The LCS of the whole strings uses 2 letters from CART
- Two letters of CART must be deleted to obtain ACT
Show the answer
B. A longest common subsequence of CART and ACT has length 2
is about prefixes: the first 4 letters of CARTOON (CART) and the first 3 of ACTION (ACT). Their longest common subsequences are AT and CT, of length 2. Every cell answers its own smaller question; only the bottom-right cell answers the original one.
The recipe
Every dynamic program so far answered the same five questions:
- State. What is a subproblem, and what exactly does one cell mean? (" is the LCS length of the first letters of and the first of .") Choosing the state is the creative part.
- Transition. How does a state's answer follow from smaller states? This transition is the recurrence.
- Base cases. Which states are answered directly?
- Order. In what order can the table be filled so that every cell's inputs come first? (Left to right; row by row; or let memoized recursion discover the order.)
- Answer. Which cell, or which combination of cells, answers the original question?
The running time is about the number of states times the work per state.
| Problem | State | Transition | States × work |
|---|---|---|---|
| Stairs | : climbs of stairs | ||
| Grid walk | : cheapest walk to cell | own cost (above, left) | |
| LCS | : LCS length of two prefixes | diagonal on a match, else max(above, left) | |
| Knapsack | : best value from the first items within weight | max(skip item , take it) |
Recognizing a DP problem
Reach for dynamic programming when you see these signals:
- "How many ways…": count the climbs, paths, tilings or decodings. Counting needs every option, which a single greedy choice cannot give.
- "Minimum cost" or "maximum value" over a sequence of choices, where each choice leaves a smaller problem of the same kind.
- "Longest" or "shortest" subsequence, path or list of edits, especially when two sequences are compared position by position.
- Choices that overlap: different early decisions lead to the same position (the same stair, the same cell, the same pair of prefixes).
- Constraints: up to a few thousand with two indices suggests an table; up to or with one index, a DP with or work per state.
Two other techniques look similar. A greedy algorithm commits to the best-looking choice and never reconsiders: fast when that is provably right, silently wrong when it is not. Divide and conquer also splits a problem into smaller ones, but its parts do not overlap: merge sort's two halves never share work, so storing their answers would save nothing. Making change with the fewest coins, the coin change problem, shows the difference between greedy and DP.
A frog crosses a river on stones , with up to . It jumps forward 1 or 2 stones at a time and pays for every stone it lands on, the first one included. Which approach finds the cheapest crossing?
- Greedy: always jump to the cheaper of the next two stones
- Sort the stones by cost and land on the cheapest ones
- DP: , filled left to right
- Divide and conquer: solve each half of the river and add the two costs
Show the answer
C. DP: , filled left to right
Every crossing reaches stone from stone or , and a cheapest crossing to extends a cheapest crossing to one of them. That is states with work each, in all. For the DP finds , which costs 2.
The map of dynamic programming
DP is one of the most widely used ideas in computing. diff and version-control tools compare files with LCS-style tables, spell checkers rank corrections by edit distance, bioinformatics aligns DNA and proteins by sequence alignment, decoders for error-correcting codes and hidden Markov models run the Viterbi algorithm, and TeX breaks paragraphs into lines with a DP over the possible breakpoints. The Optimized lessons build the toolkit:
| Optimized lesson | What you will do there |
|---|---|
| From Recursion to Dynamic Programming | Turn a recursion with overlapping subproblems into memoized code or a table, apply SRTBOT to classic problems, and count time and space exactly. |
| Sequence DP: LIS, LCS & Edit Distance | Find a longest increasing subsequence in , align two strings, and recover the edits behind diff. |
| Knapsack, Subset Sum & Coin Change | Choose items under a budget, count the ways to make change, and see why an table is not polynomial time. |
| DP on Intervals, Trees & Subsets | Use ranges, subtrees and bitmasks as states: matrix-chain order, independent sets in trees, and the traveling salesman in . |
| Counting, Probability & Games | Count modulo a prime, compute expected values, and decide who wins a game under optimal play. |
| Speeding Up Dynamic Programming | Cut transitions from to or with monotone queues, the convex hull trick and Knuth's optimization. |
Think first Memoization turns a recursion into a dynamic program automatically. So is designing a DP just writing the recursion?
Almost: the recursion is the transition, but memoizing it helps only if its arguments take few distinct values. fib() has possible arguments, so the memo table is small. A recursion whose argument is "the set of cities visited so far" has possible arguments, so its memo table, and its running time, is exponential, though still far better than trying every order. Choosing a state that captures everything the future depends on, and nothing more, is the real skill, and the Optimized lessons practice it.
Key takeaways
- Dynamic programming solves each distinct subproblem once and reuses its answer. It pays off when a recursion has overlapping subproblems, like fib's values asked exponentially often.
- Top-down DP (memoization) caches the answers of a recursion; bottom-up DP (tabulation) fills a table in an order where every cell's inputs come first. Both cost about the number of states times the work per state.
- Design a DP by answering five questions: state, transition, base cases, order and answer. A traceback through the filled table recovers the solution itself, not just its value.
- Optimal substructure, optimal solutions built from optimal solutions to subproblems, is what lets each cell keep only the best of a few options.
- Signals: "how many ways", "minimum cost" or "maximum value" over a sequence of choices, and longest or shortest subsequences. Greedy choices can fail on the same problems (coins 1, 3, 4), and divide and conquer has no overlap to reuse.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
With memoization, how does the number of steps to compute fib() grow?
- Like , the same as without memoization
- Linearly in : each of fib(0), …, fib() is computed once
- Like : each value is looked up times
- Like : memoization halves the problem at each step
Show the answer
B. Linearly in : each of fib(0), …, fib() is computed once
There are distinct subproblems, each computed once with one addition, and every other request is an cache hit. (This counts additions as single steps; for huge the numbers themselves grow to about bits.)
In the grid DP , which fill order is not valid?
- Row by row, each row from left to right
- Column by column, each column from top to bottom
- Row by row, each row from right to left
- By anti-diagonals: all cells with , then , and so on
Show the answer
C. Row by row, each row from right to left
A cell needs the cell above it and the cell to its left. Going right to left within a row reaches before has been filled. The other three orders always fill both inputs first: each is a valid order of the dependencies.
With coins , how many coins do the greedy rule (largest coin first) and dynamic programming use to pay 8?
- Greedy 2, DP 2
- Greedy 4, DP 2
- Greedy 3, DP 3
- Greedy 4, DP 3
Show the answer
B. Greedy 4, DP 2
Greedy takes the 5 and then three 1s: , four coins. DP tries every possible last coin: , which is .
Why does memoizing merge sort not make it faster?
- Merge sort is already , the best any sorting algorithm can do
- Its subproblems are all different pieces of the array, so no stored answer is ever reused
- Memoization only works for functions of a single number
- The result of a merge cannot be stored
Show the answer
B. Its subproblems are all different pieces of the array, so no stored answer is ever reused
DP saves time only when the same subproblem is asked more than once. Merge sort splits its input into disjoint halves, which split into disjoint quarters, and so on: every call sorts a different piece, so a cache would only cost memory.
An LCS table compares two strings of 2,000 and 3,000 letters. Roughly how much work does it take?
- About 5,000 cell updates, one per letter
- About 6 million cell updates, a fraction of a second
- About steps, one per pair of subsequences
- About steps, since every cell scans a whole row
Show the answer
B. About 6 million cell updates, a fraction of a second
There is one state per pair of prefix lengths: cells, each computed in from three neighbors. With the rule of thumb of about simple operations per second in compiled code, that is well under a second.
Go deeper
- From Recursion to Dynamic Programming · Overlapping subproblems, memoization, tabulation and the SRTBOT recipe.
- Sequence DP: LIS, LCS & Edit Distance · Comparing and ordering sequences one table cell at a time.
- Knapsack, Subset Sum & Coin Change · Choosing items under a budget.
- DP on Intervals, Trees & Subsets · When the subproblems are ranges, subtrees or sets.
- Counting, Probability & Games · Dynamic programs that count, average, and decide who wins.
- Speeding Up Dynamic Programming · Monotone queues, convex hulls and quadrangle inequalities.
Further reading
- J. Erickson, Algorithms (2019), chapter 3, "Dynamic Programming"; free at jeffe.cs.illinois.edu/teaching/algorithms.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 14.