Simple Algorithm
Algorithms & Data Structures · Brute Force · 18 min

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: F0=0F_0 = 0, F1=1F_1 = 1 and Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2}. The definition is already a recursive program, and a correct one. It is also hopelessly slow.

Look at what it asks. To compute F7F_7 it computes F6F_6 and F5F_5, but computing F6F_6 computes F5F_5 again, and both of them compute F4F_4. The recursion tree has a node for every call, and the same small questions appear in it over and over.

Predict before you look

The naive recursion returns fib(7) = 13. Counting every call, base cases included, how many calls does it make?

Show the answer

41

Let C(n)C(n) be the number of calls for fib(nn): C(0)=C(1)=1C(0) = C(1) = 1 and C(n)=C(n−1)+C(n−2)+1C(n) = C(n-1) + C(n-2) + 1, which gives 1,1,3,5,9,15,25,411, 1, 3, 5, 9, 15, 25, 41. In fact C(n)=2Fn+1−1C(n) = 2F_{n+1} - 1, 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 nn stairs if each move goes up one stair or two? Think about the last move. It started on stair n−1n - 1 (a single step) or on stair n−2n - 2 (a double step), and no climb is in both groups, so

ways[n]=ways[n−1]+ways[n−2].\text{ways}[n] = \text{ways}[n-1] + \text{ways}[n-2].

The base cases are ways[0]=1\text{ways}[0] = 1 (the empty climb) and ways[1]=1\text{ways}[1] = 1. Instead of recursing down from nn, 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.

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

Both versions compute each ways[i]\text{ways}[i] once, so both take O(n)O(n) 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 ways[0]=1\text{ways}[0] = 1 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 ways[0]=1\text{ways}[0] = 1 counts "one double step from the ground" exactly once, so ways[2]=1+1=2\text{ways}[2] = 1 + 1 = 2 (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 (73)=35\binom{7}{3} = 35 walks here (choose which 3 of the 7 moves go down), and on a 20×2020 \times 20 grid there are (3819)≈3.5×1010\binom{38}{19} \approx 3.5 \times 10^{10}. But every walk enters cell (r,c)(r, c) from above or from the left, so the cheapest walk to it costs

dp[r][c]=grid[r][c]+min⁡(dp[r−1][c], dp[r][c−1]),\text{dp}[r][c] = \text{grid}[r][c] + \min(\text{dp}[r-1][c],\ \text{dp}[r][c-1]),

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.

rowcol 0col 1col 2col 3col 4
037213
148516
257222
344166
The cost of each cell. A greedy walker who always steps to the cheaper neighbor goes down through 4, 5 and 4, then along the bottom row.
Think first What does the greedy walker pay in total?

3+4+5+4+4+1+6+6=333 + 4 + 5 + 4 + 4 + 1 + 6 + 6 = 33. 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: 3+7+2+1+1+2+2+6=243 + 7 + 2 + 1 + 1 + 2 + 2 + 6 = 24.

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 dp[i][j]\text{dp}[i][j] be the LCS length of the first ii letters of aa and the first jj letters of bb. Look at their last letters, a[i−1]a[i-1] and b[j−1]b[j-1]:

dp[i][j]={dp[i−1][j−1]+1if a[i−1]=b[j−1],max⁡(dp[i−1][j], dp[i][j−1])otherwise,\text{dp}[i][j] = \begin{cases} \text{dp}[i-1][j-1] + 1 & \text{if } a[i-1] = b[j-1], \\ \max\big(\text{dp}[i-1][j],\ \text{dp}[i][j-1]\big) & \text{otherwise,} \end{cases}
with dp[0][j]=dp[i][0]=0\text{dp}[0][j] = \text{dp}[i][0] = 0, since an empty prefix shares nothing. If the last letters match, keep the match; if they differ, at least one of them is not in the LCS, so drop one and keep the better result.
Check your understanding

In the CARTOON / ACTION table, dp[4][3]=2\text{dp}[4][3] = 2. What does that cell say?

  1. CARTOON and ACTION have exactly 2 letters in common
  2. A longest common subsequence of CART and ACT has length 2
  3. The LCS of the whole strings uses 2 letters from CART
  4. 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

dp[i][j]\text{dp}[i][j] 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:

  1. State. What is a subproblem, and what exactly does one cell mean? ("dp[i][j]\text{dp}[i][j] is the LCS length of the first ii letters of aa and the first jj of bb.") Choosing the state is the creative part.
  2. Transition. How does a state's answer follow from smaller states? This transition is the recurrence.
  3. Base cases. Which states are answered directly?
  4. 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.)
  5. 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.

ProblemStateTransitionStates × work
Stairsways[i]\text{ways}[i]: climbs of ii stairsways[i−1]+ways[i−2]\text{ways}[i-1] + \text{ways}[i-2]n×O(1)n \times O(1)
Grid walkdp[r][c]\text{dp}[r][c]: cheapest walk to cell (r,c)(r, c)own cost +min⁡+ \min(above, left)RC×O(1)RC \times O(1)
LCSdp[i][j]\text{dp}[i][j]: LCS length of two prefixesdiagonal +1+ 1 on a match, else max(above, left)nm×O(1)nm \times O(1)
Knapsackdp[i][w]\text{dp}[i][w]: best value from the first ii items within weight wwmax(skip item ii, take it)nW×O(1)nW \times O(1)
The last row is a preview: the knapsack problem, packing the most valuable load under a weight limit, has its own Optimized lesson.

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: nn up to a few thousand with two indices suggests an O(n2)O(n^2) table; nn up to 10510^5 or 10610^6 with one index, a DP with O(1)O(1) or O(log⁡n)O(\log n) 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.

Check your understanding

A frog crosses a river on stones 0,1,…,n−10, 1, \dots, n-1, with nn up to 10510^5. It jumps forward 1 or 2 stones at a time and pays c[i]c[i] for every stone it lands on, the first one included. Which approach finds the cheapest crossing?

  1. Greedy: always jump to the cheaper of the next two stones
  2. Sort the stones by cost and land on the cheapest ones
  3. DP: best[i]=c[i]+min⁡(best[i−1],best[i−2])\text{best}[i] = c[i] + \min(\text{best}[i-1], \text{best}[i-2]), filled left to right
  4. Divide and conquer: solve each half of the river and add the two costs
Show the answer

C. DP: best[i]=c[i]+min⁡(best[i−1],best[i−2])\text{best}[i] = c[i] + \min(\text{best}[i-1], \text{best}[i-2]), filled left to right

Every crossing reaches stone ii from stone i−1i - 1 or i−2i - 2, and a cheapest crossing to ii extends a cheapest crossing to one of them. That is nn states with O(1)O(1) work each, O(n)O(n) in all. For c=[0,1,2,100,0]c = [0, 1, 2, 100, 0] the DP finds 0→2→40 \to 2 \to 4, 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 lessonWhat you will do there
From Recursion to Dynamic ProgrammingTurn 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 DistanceFind a longest increasing subsequence in O(nlog⁡n)O(n \log n), align two strings, and recover the edits behind diff.
Knapsack, Subset Sum & Coin ChangeChoose items under a budget, count the ways to make change, and see why an O(nW)O(nW) table is not polynomial time.
DP on Intervals, Trees & SubsetsUse ranges, subtrees and bitmasks as states: matrix-chain order, independent sets in trees, and the traveling salesman in O(2nn2)O(2^n n^2).
Counting, Probability & GamesCount modulo a prime, compute expected values, and decide who wins a game under optimal play.
Speeding Up Dynamic ProgrammingCut transitions from O(n)O(n) to O(1)O(1) or O(log⁡n)O(\log n) with monotone queues, the convex hull trick and Knuth's optimization.
Each Optimized lesson leads to three Optimal deep dives, from Hirschberg's linear-space alignment to the conditional lower bounds suggesting that edit distance cannot be computed in much less than quadratic time.
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(nn) has n+1n + 1 possible arguments, so the memo table is small. A recursion whose argument is "the set of cities visited so far" has 2n2^n 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 n+1n + 1 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.

Question 1

With memoization, how does the number of steps to compute fib(nn) grow?

  1. Like 1.618n1.618^n, the same as without memoization
  2. Linearly in nn: each of fib(0), …, fib(nn) is computed once
  3. Like n2n^2: each value is looked up nn times
  4. Like log⁡n\log n: memoization halves the problem at each step
Show the answer

B. Linearly in nn: each of fib(0), …, fib(nn) is computed once

There are n+1n + 1 distinct subproblems, each computed once with one addition, and every other request is an O(1)O(1) cache hit. (This counts additions as single steps; for huge nn the numbers themselves grow to about 0.69n0.69n bits.)

Question 2

In the grid DP dp[r][c]=grid[r][c]+min⁡(dp[r−1][c],dp[r][c−1])\text{dp}[r][c] = \text{grid}[r][c] + \min(\text{dp}[r-1][c], \text{dp}[r][c-1]), which fill order is not valid?

  1. Row by row, each row from left to right
  2. Column by column, each column from top to bottom
  3. Row by row, each row from right to left
  4. By anti-diagonals: all cells with r+c=0r + c = 0, then r+c=1r + c = 1, 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 dp[r][c]\text{dp}[r][c] before dp[r][c−1]\text{dp}[r][c-1] has been filled. The other three orders always fill both inputs first: each is a valid order of the dependencies.

Question 3

With coins {1,4,5}\{1, 4, 5\}, how many coins do the greedy rule (largest coin first) and dynamic programming use to pay 8?

  1. Greedy 2, DP 2
  2. Greedy 4, DP 2
  3. Greedy 3, DP 3
  4. Greedy 4, DP 3
Show the answer

B. Greedy 4, DP 2

Greedy takes the 5 and then three 1s: 5+1+1+15 + 1 + 1 + 1, four coins. DP tries every possible last coin: best[8]=1+min⁡(best[7],best[4],best[3])=1+min⁡(3,1,3)=2\text{best}[8] = 1 + \min(\text{best}[7], \text{best}[4], \text{best}[3]) = 1 + \min(3, 1, 3) = 2, which is 4+44 + 4.

Question 4

Why does memoizing merge sort not make it faster?

  1. Merge sort is already O(nlog⁡n)O(n \log n), the best any sorting algorithm can do
  2. Its subproblems are all different pieces of the array, so no stored answer is ever reused
  3. Memoization only works for functions of a single number
  4. 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.

Question 5

An LCS table compares two strings of 2,000 and 3,000 letters. Roughly how much work does it take?

  1. About 5,000 cell updates, one per letter
  2. About 6 million cell updates, a fraction of a second
  3. About 250002^{5000} steps, one per pair of subsequences
  4. About 2.7×10102.7 \times 10^{10} 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: 2001×3001≈6×1062001 \times 3001 \approx 6 \times 10^6 cells, each computed in O(1)O(1) from three neighbors. With the rule of thumb of about 10810^8 simple operations per second in compiled code, that is well under a second.

Go deeper

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.