Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

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 9.3×10209.3 \times 10^{20} 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 ii 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.

python
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 0,…,n−10, \dots, n-1 hold a[i]≥0a[i] \ge 0 dollars, and you may take the money from any set of houses with no two adjacent. Maximize the total.

PartQuestionHouse robber
SubproblemsWhat do I remember?x(i)x(i) = the most money from the first ii houses, 0≤i≤n0 \le i \le n (a state for each prefix)
RelateHow does a subproblem follow from smaller ones?x(i)=max⁡(x(i−1), x(i−2)+a[i−1])x(i) = \max\big(x(i-1),\ x(i-2) + a[i-1]\big): skip house i−1i-1, or rob it and skip house i−2i-2
Topological orderIn what order are inputs ready?i=0,1,…,ni = 0, 1, \dots, n
Base casesWhich subproblems have no smaller ones?x(0)=0x(0) = 0 and x(1)=a[0]x(1) = a[0]
Original problemWhere is the answer?x(n)x(n), plus a traceback for the set of houses itself
TimeSubproblems × work each(n+1)×O(1)=O(n)(n + 1) \times O(1) = O(n)
The relation is the transition. Writing it as a choice between cases ("skip or take") is the most common pattern in all of DP.
DerivationThe house-robber relation is correct
  1. value(S) ≤ max⁡(x(i−1), x(i−2)+a[i−1])\text{value}(S)\ \le\ \max\big(x(i-1),\ x(i-2) + a[i-1]\big)

    No set beats it. Let SS be any valid set among the first i≥2i \ge 2 houses. If SS skips house i−1i-1, it is a valid set among the first i−1i-1 houses. If SS robs house i−1i-1, it skips house i−2i-2, so SS without house i−1i-1 is a valid set among the first i−2i-2 houses:

  2. x(i) ≥ max⁡(x(i−1), x(i−2)+a[i−1])x(i)\ \ge\ \max\big(x(i-1),\ x(i-2) + a[i-1]\big)

    Both options are achievable. A best set for the first i−1i-1 houses is valid for the first ii. A best set for the first i−2i-2 houses, plus house i−1i-1, is valid too, because house i−2i-2 is not in it:

  3. x(i)=max⁡(x(i−1), x(i−2)+a[i−1]),x(0)=0,  x(1)=a[0]x(i) = \max\big(x(i-1),\ x(i-2) + a[i-1]\big),\qquad x(0) = 0,\ \ x(1) = a[0]

    So equality holds for every i≥2i \ge 2. The base cases are right because the amounts are non-negative (x(1)=a[0]≥0x(1) = a[0] \ge 0), and the theorem above makes the whole table correct.

Predict before you look

For a=[6,1,2,10,4,3,8]a = [6, 1, 2, 10, 4, 3, 8], what is x(7)x(7), the most the thief can take?

Show the answer

24

The table is x=0,6,6,8,16,16,19,24x = 0, 6, 6, 8, 16, 16, 19, 24. For instance x(4)=max⁡(x(3),x(2)+10)=max⁡(8,16)=16x(4) = \max(x(3), x(2) + 10) = \max(8, 16) = 16, and x(7)=max⁡(x(6),x(5)+8)=max⁡(19,24)=24x(7) = \max(x(6), x(5) + 8) = \max(19, 24) = 24: houses 0, 3 and 6. Here "richest house first" happens to give 24 as well, but on [3,4,3][3, 4, 3] it takes the 4, while 3+3=63 + 3 = 6 is better.

python
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 6

SRTBOT 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 max⁡\max: if every solution falls into exactly one case of the relation, the counts of the cases add up. Two classics:

PartGrid walks around obstaclesDecode ways
SP(r,c)P(r, c) = the number of right/down walks from (0,0)(0, 0) to (r,c)(r, c)D(i)D(i) = the number of ways to decode the first ii digits, with A = 1, …, Z = 26
RP(r,c)=0P(r, c) = 0 on a blocked cell, else P(r−1,c)+P(r,c−1)P(r-1, c) + P(r, c-1)D(i)=[si−1≠0] D(i−1)+[10≤si−2si−1‾≤26] D(i−2)D(i) = [s_{i-1} \ne 0]\,D(i-1) + [10 \le \overline{s_{i-2}s_{i-1}} \le 26]\,D(i-2)
TRow by row, left to righti=0,1,…,ni = 0, 1, \dots, n
BP(0,0)=1P(0, 0) = 1 if it is open; neighbors outside the grid count 0D(0)=1D(0) = 1, the empty prefix
OP(R−1,C−1)P(R-1, C-1)D(n)D(n)
TO(RC)O(RC)O(n)O(n)
[⋅][\cdot] is 1 when the condition holds and 0 otherwise, and si−2si−1‾\overline{s_{i-2}s_{i-1}} is the two-digit number formed by the last two digits. The cases split the solutions cleanly: a walk enters a cell from above or from the left, never both, and the last letter of a decoding uses one digit or two.
rowcol 0col 1col 2col 3col 4
0start····
1·#···
2···#·
3····end
A 4 × 5 grid with two blocked cells (#).
Predict before you look

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 PP row by row: [1,1,1,1,1][1, 1, 1, 1, 1], then [1,0,1,2,3][1, 0, 1, 2, 3], then [1,1,2,0,3][1, 1, 2, 0, 3], then [1,2,4,4,7][1, 2, 4, 4, 7]. Without the obstacles there would be (73)=35\binom{7}{3} = 35 walks; the blocked cells are 0, so walks through them are never counted.

python
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

T=∑subproblems swork(s) ≤ (number of subproblems)×(most work per subproblem).T = \sum_{\text{subproblems } s} \text{work}(s) \ \le\ (\text{number of subproblems}) \times (\text{most work per subproblem}).

For house robber that is O(n)O(n). When the work varies, add it up. The table for the longest increasing subsequence, lis[i]=1+max⁡{lis[j]:j<i, a[j]<a[i]}\text{lis}[i] = 1 + \max\{\text{lis}[j] : j < i,\ a[j] < a[i]\}, spends about ii steps on subproblem ii, so T=Θ(n2)T = \Theta(n^2). 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.

python
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 r−1r - 1 (the cell above) and P[c - 1] already holds row rr (the cell to the left): one array serves as both rows. On the grid above it returns 7.

Check your understanding

A DP has one state (i,j)(i, j) for every pair 0≤i≤j<n0 \le i \le j < n, and evaluating state (i,j)(i, j) takes O(j−i+1)O(j - i + 1) time (it tries every split point between ii and jj). What is the total running time?

  1. Θ(n2)\Theta(n^2)
  2. Θ(n2log⁡n)\Theta(n^2 \log n)
  3. Θ(n3)\Theta(n^3)
  4. Θ(2n)\Theta(2^n)
Show the answer

C. Θ(n3)\Theta(n^3)

Sum the work: there are n−L+1n - L + 1 states of length L=j−i+1L = j - i + 1, so T=∑L=1n(n−L+1) L=n(n+1)(n+2)/6=Θ(n3)T = \sum_{L=1}^{n} (n - L + 1)\,L = n(n+1)(n+2)/6 = \Theta(n^3). 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?

AspectTop-down (memoized recursion)Bottom-up (a table and loops)
Order of evaluationFound automatically by the recursionYou must choose a topological order
Subproblems computedOnly those reachable from the original problemAll of them, needed or not
OverheadA call and a cache lookup per subproblemA tight loop over an array
StackAs deep as the longest chain of dependencies: nn frames for fibNone
Saving space and timeHard: the whole memo stays aliveRolling arrays, and later monotone queues and convex hulls
Top-down shines when few states are reachable or the order is awkward to write down; bottom-up shines when every state is needed and nn is large.

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 10510^5 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 10510^5 small C++ frames but not 10710^7. When the chain of dependencies is long, write the loop.

cpp
#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 −1-1 by memset (every byte 0xFF makes the integer −1-1), 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 1000×10001000 \times 1000 grid has (1998999)≈5×10599\binom{1998}{999} \approx 5 \times 10^{599} 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: nn up to 10510^5 or 10610^6 with O(1)O(1) work per state; n≤5000n \le 5000 for n2n^2 states; a budget WW up to about 10510^5 for nWnW states; n≤20n \le 20 for subsets stored as bitmasks.
  • "Modulo 109+710^9 + 7": almost always a count, and counts rarely have a greedy shortcut.
Problem (in brief)State and relationCost
Cheapest way up a staircase, paying cost[i]\text{cost}[i] to leave stair ii, moving 1 or 2 stairsc(i)=min⁡(c(i−1)+cost[i−1], c(i−2)+cost[i−2])c(i) = \min\big(c(i-1) + \text{cost}[i-1],\ c(i-2) + \text{cost}[i-2]\big)O(n)O(n)
Most money from non-adjacent housesx(i)=max⁡(x(i−1), x(i−2)+a[i−1])x(i) = \max\big(x(i-1),\ x(i-2) + a[i-1]\big)O(n)O(n)
Number of decodings of a digit stringD(i)=D(i−1)+D(i−2)D(i) = D(i-1) + D(i-2), each term only if its letter is validO(n)O(n)
Number of grid walks around obstaclesP(r,c)=P(r−1,c)+P(r,c−1)P(r, c) = P(r-1, c) + P(r, c-1), 0 on blocked cellsO(RC)O(RC)
Largest sum of a contiguous subarrayBest sum ending at ii: e(i)=a[i]+max⁡(e(i−1),0)e(i) = a[i] + \max(e(i-1), 0), Kadane's algorithmO(n)O(n)
Five classics, each a one-index or two-index table with O(1)O(1) work per state.
Check your understanding

Given n≤104n \le 10^4, find the fewest perfect squares (1,4,9,…1, 4, 9, \dots) that add up to nn. Which approach is correct and fast enough?

  1. Greedy: subtract the largest square that fits, and repeat
  2. DP: best[m]=1+min⁡k2≤mbest[m−k2]\text{best}[m] = 1 + \min_{k^2 \le m} \text{best}[m - k^2] for m=1,…,nm = 1, \dots, n
  3. Binary search on the number of squares
  4. Two pointers over the sorted list of squares
Show the answer

B. DP: best[m]=1+min⁡k2≤mbest[m−k2]\text{best}[m] = 1 + \min_{k^2 \le m} \text{best}[m - k^2] for m=1,…,nm = 1, \dots, n

It is coin change with the squares as coins. There are nn states, each trying about m\sqrt m last squares: about nn≈106n\sqrt n \approx 10^6 steps for n=104n = 10^4. For n=12n = 12 the DP finds 4+4+44 + 4 + 4, 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.

Question 1

In house robber, x(i)=max⁡(x(i−1),x(i−2)+a[i−1])x(i) = \max(x(i-1), x(i-2) + a[i-1]) for i≥2i \ge 2. A friend sets the base cases to x(0)=0x(0) = 0 and x(1)=0x(1) = 0. What goes wrong?

  1. Nothing: base cases do not affect the final answer
  2. House 0 can never be robbed, so for a=[5,1]a = [5, 1] the answer comes out 1 instead of 5
  3. The loop never terminates
  4. The answer is always 0
Show the answer

B. House 0 can never be robbed, so for a=[5,1]a = [5, 1] the answer comes out 1 instead of 5

x(1)x(1) must be the best total from house 0 alone, which is a[0]a[0]. With x(1)=0x(1) = 0, x(2)=max⁡(0,0+1)=1x(2) = \max(0, 0 + 1) = 1, and the 5 is lost. Every value is built from the base cases, so an error there spreads through the table.

Question 2

Subproblem ii of a DP, for i=1,…,ni = 1, \dots, n, reads every subproblem j<ij < i and does O(1)O(1) work per value read. What is its running time?

  1. Θ(n)\Theta(n)
  2. Θ(nlog⁡n)\Theta(n \log n)
  3. Θ(n2)\Theta(n^2)
  4. Θ(2n)\Theta(2^n)
Show the answer

C. Θ(n2)\Theta(n^2)

Time is the sum of the work over the subproblems: ∑i=1n(i−1)=n(n−1)/2=Θ(n2)\sum_{i=1}^{n} (i - 1) = n(n-1)/2 = \Theta(n^2). The O(n2)O(n^2) table for the longest increasing subsequence has exactly this shape.

Question 3

A memoized Python recursion over n=106n = 10^6 states, each depending on the previous one, crashes. What is the most likely cause, and the fix?

  1. The memo dictionary is too large; store it in a list instead
  2. The chain of calls is 10610^6 deep, beyond the recursion limit and the C stack; rewrite it as a bottom-up loop
  3. Memoization stops working beyond 10510^5 states; switch to plain recursion
  4. Python integers overflow; take the results modulo 109+710^9 + 7
Show the answer

B. The chain of calls is 10610^6 deep, beyond the recursion limit and the C stack; rewrite it as a bottom-up loop

Top-down evaluation first descends the whole chain: 10610^6 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.

Question 4

You replace the house-robber table by two variables, a rolling array. What do you lose?

  1. Correctness for streets of more than 2 houses
  2. The ability to read off which houses to rob without extra work
  3. The O(n)O(n) running time
  4. 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 O(n)O(n) time and O(1)O(1) space. But the traceback, which walks back through x(n),x(n−1),…x(n), x(n-1), \dots 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

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.