From Recursion to Dynamic Programming
Overlapping subproblems, memoization, tabulation and the SRTBOT recipe.
A street has 100 houses with cash inside, and a thief may rob any set of them with no two next door to each other: about possible sets. Dynamic programming finds the best one in 100 steps by asking a single question per house: what is the most I can take from the first houses? This lesson turns questions like that into a recipe, SRTBOT, and practices it until it is routine.
What you’ll learn
- Identify overlapping subproblems and optimal substructure, and turn a recursive solution into memoized (top-down) or tabulated (bottom-up) code.
- Apply SRTBOT (subproblems, relate, topological order, base cases, original problem, time) to classic problems, and prove a recurrence correct by induction.
- Count a DP's running time as the sum of the work over its subproblems, and cut its space with rolling arrays.
- Choose between top-down and bottom-up evaluation, and recognize DP problems, and their look-alikes, from the statement and the constraints.
Recurse, but reuse
A dynamic program needs two properties:
- Overlapping subproblems: a natural recursion asks the same subproblems many times, while the number of distinct subproblems is small (typically polynomial).
- Optimal substructure: the answer to a subproblem follows from the answers to smaller subproblems, so an optimal solution is assembled from optimal solutions to its parts.
Given both, evaluate each distinct subproblem once. Top-down, memoization wraps the recursion in a cache: look a subproblem up before computing it, and store it after. Bottom-up, tabulation fills an array in an order where every entry's inputs are already there.
from functools import cache
def fib_naive(n): # 2F(n+1) - 1 calls: exponential
return n if n <= 1 else fib_naive(n - 1) + fib_naive(n - 2)
memo = {}
def fib_memo(n): # top-down: each n computed once
if n <= 1:
return n
if n not in memo:
memo[n] = fib_memo(n - 1) + fib_memo(n - 2)
return memo[n]
@cache # the same, from the standard library
def fib_cached(n):
return n if n <= 1 else fib_cached(n - 1) + fib_cached(n - 2)
def fib_table(n): # bottom-up: no recursion at all
F = [0, 1] + [0] * max(0, n - 1)
for i in range(2, n + 1):
F[i] = F[i - 1] + F[i - 2]
return F[n]All four return the same values. Only the naive one makes exponentially many calls; a cache keyed by the arguments is the whole difference.
SRTBOT on one problem
MIT's introductory algorithms course organizes every dynamic program into six parts, SRTBOT. Here they are for the house-robber problem: houses hold dollars, and you may take the money from any set of houses with no two adjacent. Maximize the total.
| Part | Question | House robber |
|---|---|---|
| Subproblems | What do I remember? | = the most money from the first houses, (a state for each prefix) |
| Relate | How does a subproblem follow from smaller ones? | : skip house , or rob it and skip house |
| Topological order | In what order are inputs ready? | |
| Base cases | Which subproblems have no smaller ones? | and |
| Original problem | Where is the answer? | , plus a traceback for the set of houses itself |
| Time | Subproblems × work each |
No set beats it. Let be any valid set among the first houses. If skips house , it is a valid set among the first houses. If robs house , it skips house , so without house is a valid set among the first houses:
Both options are achievable. A best set for the first houses is valid for the first . A best set for the first houses, plus house , is valid too, because house is not in it:
So equality holds for every . The base cases are right because the amounts are non-negative (), and the theorem above makes the whole table correct.
For , what is , the most the thief can take?
Show the answer
24
The table is . For instance , and : houses 0, 3 and 6. Here "richest house first" happens to give 24 as well, but on it takes the 4, while is better.
def rob(a):
n = len(a)
x = [0] * (n + 1) # x[i]: best total from houses 0..i-1
if n:
x[1] = a[0]
for i in range(2, n + 1): # topological order: increasing i
x[i] = max(x[i - 1], x[i - 2] + a[i - 1])
return x[n]
print(rob([6, 1, 2, 10, 4, 3, 8])) # 24: houses 0, 3 and 6SRTBOT read straight into code: the array is S, the loop body is R, the loop direction is T, the two initial entries are B, and the return is O.
Same recipe, other problems
Counting problems use the same recipe with in place of : if every solution falls into exactly one case of the relation, the counts of the cases add up. Two classics:
| Part | Grid walks around obstacles | Decode ways |
|---|---|---|
| S | = the number of right/down walks from to | = the number of ways to decode the first digits, with A = 1, …, Z = 26 |
| R | on a blocked cell, else | |
| T | Row by row, left to right | |
| B | if it is open; neighbors outside the grid count 0 | , the empty prefix |
| O | ||
| T |
| row | col 0 | col 1 | col 2 | col 3 | col 4 |
|---|---|---|---|---|---|
| 0 | start | · | · | · | · |
| 1 | · | # | · | · | · |
| 2 | · | · | · | # | · |
| 3 | · | · | · | · | end |
How many right/down walks go from the start to the end of this grid without entering a blocked cell?
Show the answer
7
Fill row by row: , then , then , then . Without the obstacles there would be walks; the blocked cells are 0, so walks through them are never counted.
def decodings(s): # s: a string of digits
D = [0] * (len(s) + 1)
D[0] = 1 # the empty prefix: one decoding
for i in range(1, len(s) + 1):
if s[i - 1] != '0':
D[i] += D[i - 1] # the last letter uses one digit
if i >= 2 and '10' <= s[i - 2:i] <= '26':
D[i] += D[i - 2] # the last letter uses two digits
return D[-1]
print(decodings('226'), decodings('11106'), decodings('06')) # 3 2 0"226" decodes as BBF, BZ and VF. A 0 can only end a two-digit letter (10 or 20), so "06" has no decoding at all.
Time and space
Time. Each subproblem costs the work of evaluating its relation once its inputs are known, so the total is
For house robber that is . When the work varies, add it up. The table for the longest increasing subsequence, , spends about steps on subproblem , so . Memoized recursion adds a dictionary lookup per call, a constant factor.
Space. A table holds one entry per subproblem, but a relation often reads only a few recent entries. Keeping just those is a rolling array: house robber needs two numbers, a grid walk one row, an LCS table two rows.
def rob(a): # O(1) space: only x(i-2) and x(i-1)
prev, cur = 0, 0
for v in a:
prev, cur = cur, max(cur, prev + v)
return cur
def walks(grid): # O(C) space: one row, updated in place
P = [0] * len(grid[0])
P[0] = 1 # the start, if it is open
for row in grid: # grid[r][c] == 1 means blocked
for c, blocked in enumerate(row):
if blocked:
P[c] = 0
elif c > 0:
P[c] += P[c - 1] # old P[c] is from above, P[c-1] from the left
return P[-1]In walks, before the update P[c] still holds row (the cell above) and P[c - 1] already holds row (the cell to the left): one array serves as both rows. On the grid above it returns 7.
A DP has one state for every pair , and evaluating state takes time (it tries every split point between and ). What is the total running time?
Show the answer
C.
Sum the work: there are states of length , so . This is the shape of interval DP, such as matrix-chain multiplication, met in the lesson DP on Intervals, Trees & Subsets.
Top-down or bottom-up?
| Aspect | Top-down (memoized recursion) | Bottom-up (a table and loops) |
|---|---|---|
| Order of evaluation | Found automatically by the recursion | You must choose a topological order |
| Subproblems computed | Only those reachable from the original problem | All of them, needed or not |
| Overhead | A call and a cache lookup per subproblem | A tight loop over an array |
| Stack | As deep as the longest chain of dependencies: frames for fib | None |
| Saving space and time | Hard: the whole memo stays alive | Rolling arrays, and later monotone queues and convex hulls |
Stack depth is the practical trap. CPython stops at 1,000 nested calls by default (sys.getrecursionlimit()), so a memoized recursion along a chain of states raises RecursionError; raising the limit far enough can crash the interpreter instead, because its C stack is small. A native main thread typically gets about 8 MB of stack on Linux and 1 MB on Windows, enough for roughly small C++ frames but not . When the chain of dependencies is long, write the loop.
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
using namespace std;
const long long MOD = 1'000'000'007;
int R, C;
vector<string> g; // '#' marks a blocked cell
long long memo[1000][1000]; // -1 = not computed yet
long long topDown(int r, int c) { // walks from (0, 0) to (r, c), mod MOD
if (r < 0 || c < 0 || g[r][c] == '#') return 0;
if (r == 0 && c == 0) return 1;
long long &m = memo[r][c];
if (m != -1) return m; // computed before: reuse it
return m = (topDown(r - 1, c) + topDown(r, c - 1)) % MOD;
}
long long bottomUp() { // one row, updated in place
vector<long long> P(C, 0);
P[0] = 1;
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++)
if (g[r][c] == '#') P[c] = 0;
else if (c > 0) P[c] = (P[c] + P[c - 1]) % MOD;
return P[C - 1];
}
int main() {
g = {".....", ".#...", "...#.", "....."};
R = g.size(); C = g[0].size();
memset(memo, -1, sizeof memo); // all bytes 0xFF: every entry reads -1
printf("%lld %lld\n", topDown(R - 1, C - 1), bottomUp()); // 7 7
}The contest idioms: a global memo filled with by memset (every byte 0xFF makes the integer ), a reference m into the memo so the result is stored as it is returned, and long long with a modulus, because walk counts outgrow 64 bits fast: an open grid has walks.
Recognizing it
Reach for a DP when you see these signals:
- An optimum or a count over sequences of decisions: "minimum cost", "maximum total", "number of ways", "is it possible".
- A brute-force recursion whose arguments repeat: write the exponential recursion first; if its arguments take few distinct values (an index, a pair of indices, a remaining amount), memoize it.
- Constraints that fit a table: up to or with work per state; for states; a budget up to about for states; for subsets stored as bitmasks.
- "Modulo ": almost always a count, and counts rarely have a greedy shortcut.
| Problem (in brief) | State and relation | Cost |
|---|---|---|
| Cheapest way up a staircase, paying to leave stair , moving 1 or 2 stairs | ||
| Most money from non-adjacent houses | ||
| Number of decodings of a digit string | , each term only if its letter is valid | |
| Number of grid walks around obstacles | , 0 on blocked cells | |
| Largest sum of a contiguous subarray | Best sum ending at : , Kadane's algorithm |
Given , find the fewest perfect squares () that add up to . Which approach is correct and fast enough?
- Greedy: subtract the largest square that fits, and repeat
- DP: for
- Binary search on the number of squares
- Two pointers over the sorted list of squares
Show the answer
B. DP: for
It is coin change with the squares as coins. There are states, each trying about last squares: about steps for . For the DP finds , three squares, and by Lagrange's four-square theorem the answer is never more than 4.
Key takeaways
- A DP needs overlapping subproblems (few distinct subproblems, asked many times) and optimal substructure (a subproblem's answer follows from smaller ones).
- SRTBOT: Subproblems, Relate, Topological order, Base cases, Original problem, Time. Correctness is induction along the topological order: correct base cases plus a correct relation give a correct table.
- Time is the sum of the work over all subproblems, not just their number. Rolling arrays keep only the entries the relation can still read, at the price of the traceback.
- Top-down evaluation computes only the reachable states and finds the order by itself, but costs recursion depth; bottom-up loops are fast, use no stack, and make space and speed tricks possible.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In house robber, for . A friend sets the base cases to and . What goes wrong?
- Nothing: base cases do not affect the final answer
- House 0 can never be robbed, so for the answer comes out 1 instead of 5
- The loop never terminates
- The answer is always 0
Show the answer
B. House 0 can never be robbed, so for the answer comes out 1 instead of 5
must be the best total from house 0 alone, which is . With , , and the 5 is lost. Every value is built from the base cases, so an error there spreads through the table.
Subproblem of a DP, for , reads every subproblem and does work per value read. What is its running time?
Show the answer
C.
Time is the sum of the work over the subproblems: . The table for the longest increasing subsequence has exactly this shape.
A memoized Python recursion over states, each depending on the previous one, crashes. What is the most likely cause, and the fix?
- The memo dictionary is too large; store it in a list instead
- The chain of calls is deep, beyond the recursion limit and the C stack; rewrite it as a bottom-up loop
- Memoization stops working beyond states; switch to plain recursion
- Python integers overflow; take the results modulo
Show the answer
B. The chain of calls is deep, beyond the recursion limit and the C stack; rewrite it as a bottom-up loop
Top-down evaluation first descends the whole chain: nested calls. CPython's default recursion limit is 1,000, and raising it that far can overflow the interpreter's own C stack. A loop in topological order uses no stack at all, and it is faster too.
You replace the house-robber table by two variables, a rolling array. What do you lose?
- Correctness for streets of more than 2 houses
- The ability to read off which houses to rob without extra work
- The running time
- Nothing: the table was only needed for memoization
Show the answer
B. The ability to read off which houses to rob without extra work
The total is still right, in time and space. But the traceback, which walks back through to see which option won, needs the old values. Keep the table, record one choice bit per house, or recompute: the Optimal lesson on reconstruction compares these options.
Go deeper
- Designing States & Transitions · Choosing what to remember: prefixes, suffixes, ranges and extra parameters.
- Reconstructing Solutions & Saving Space · Parent pointers, rolling arrays and Hirschberg’s linear-space trick.
- DP as Shortest Paths in a DAG · The subproblem graph, Bellman’s principle, and when DP cannot work.
Further reading
- R. Bellman, Dynamic Programming (Princeton University Press, 1957).
- E. Demaine, J. Ku & J. Solomon, 6.006 Introduction to Algorithms, Spring 2020, lectures 15–18 on dynamic programming (MIT OpenCourseWare).
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 14.
- J. Kleinberg & É. Tardos, Algorithm Design (Addison-Wesley, 2005), chapter 6.