Dynamic Programming

In one sentence

When the best answer is built from best answers to smaller subproblems, and those subproblems repeat, solve each one once and store it: exponential recursion becomes polynomial.

Naive recursion re-solves fib(3) and fib(2). With a memo, each of the n + 1 states is computed once, and the call tree collapses into this DAG.

How it works

  • The two properties are optimal substructure and overlapping subproblems; without repeats, it's plain divide and conquer.
  • Define the state, the recurrence, the base cases and the cell holding the answer.
  • Top-down: recursion plus @cache. Bottom-up: fill a table in dependency order.
  • Time = states × work per state; keeping only one row cuts memory.
  • Signals: count the ways, min/max cost or feasibility, where greedy can fail.

Check yourself

Answer to mark it learned; your answers aren't scored.

A recursive solution for "fewest coins to make 10,000 from coins [1, 5, 7]" times out. A trace shows solve(9993) evaluated thousands of times. Best fix?

Go deeper

Big-O growth Interactive lab
Solve it in Python 18
Full explanation

DP applies when a problem has two properties:

  • Optimal substructure: the best answer combines best answers to subproblems.
  • Overlapping subproblems: the same subproblems recur, so storing them pays.

Write it in four steps: the state (what dp[i][j] means), the recurrence, the base cases and the cell that holds the answer. Then pick a style:

  • Top-down: plain recursion plus @cache. Quick to write and only visits reachable states, but uses the call stack.
  • Bottom-up: fill a table in dependency order. No recursion, and often only the previous row is needed.

Classic tables: 0/1 knapsack dp[i][w] (best value from the first i items within capacity w), LCS dp[i][j] over two prefixes, edit distance dp[i][j] (edits to turn a[:i] into b[:j]). Cost = number of states × work per state.

Signals: "count the ways", "minimum/maximum cost", "is it possible", over sequences, grids or capacities, where a greedy choice can be wrong.

Code Top-down memo, 2D edit distance, 1D knapsack
pythonTop-down memo, 2D edit distance, 1D knapsack
from functools import cache

@cache                                   # top-down: plain recursion + memo
def ways(n: int) -> int:                 # climb n stairs taking 1 or 2 steps
    return 1 if n <= 1 else ways(n - 1) + ways(n - 2)

def edit_distance(a: str, b: str) -> int:
    m, n = len(a), len(b)
    # dp[i][j] = edits to turn a[:i] into b[:j]; one list per row (no aliasing)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m + 1):
        dp[i][0] = i                     # delete all of a[:i]
    for j in range(n + 1):
        dp[0][j] = j                     # insert all of b[:j]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:                        # delete, insert, replace
                dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
    return dp[m][n]

def knapsack(items, cap: int) -> int:    # 0/1: items = [(weight, value)]
    best = [0] * (cap + 1)               # one row: best value per capacity
    for w, v in items:
        for c in range(cap, w - 1, -1):  # go DOWN so each item is used once
            best[c] = max(best[c], best[c - w] + v)
    return best[cap]
Real example

Edit distance. Turn "horse" into "ros" with the fewest single-character inserts, deletes or replaces. dp[i][j] = edits for the first i letters of one and the first j of the other: if the letters match, copy the diagonal; otherwise take 1 + min(up, left, diagonal). The table has 6 × 4 = 24 cells at O(1) each, and dp[5][3] = 3 (replace h→r, delete r, delete e). The naive recursion branches three ways on every mismatch: exponential.

Trade-offs +3 · −3

+ You gain

  • Turns exponential brute force into polynomial time (Fibonacci: ~O(2ⁿ) → O(n)).
  • Top-down is a mechanical upgrade of a correct recursive solution.
  • Bottom-up avoids recursion limits and often shrinks to one row of memory.

− You pay

  • Choosing the state is the hard part; a wrong state is silently wrong.
  • Memory grows with the state space: O(m·n) for two strings.
  • Pseudo-polynomial when a dimension is a number: knapsack's O(n·W) explodes for large W.

Use it when

Count the ways, minimum/maximum cost or feasibility over prefixes, intervals, grids or capacities, when choices interact (greedy can fail) and brute-force recursion repeats subproblems.

Avoid it when

Subproblems don't repeat (divide and conquer, like merge sort), a greedy choice is provably optimal (interval scheduling), or the state space is too large to store.

Numbers to know 4
  • Time = states × work per state: LCS and edit distance O(m·n); 0/1 knapsack O(n·W).
  • Fibonacci: naive recursion ~O(2ⁿ) calls; memoized O(n).
  • Two rolling rows cut edit distance memory from O(m·n) to O(min(m, n)).
  • CPython's default recursion limit is 1,000 frames.
Common pitfalls 4
  • [[0] * n] * m makes m references to one row: a write shows up in every row.
  • 1D 0/1 knapsack looping capacity upward reuses items (that's unbounded knapsack).
  • Off-by-one between string and table indexes: dp[i][j] covers a[:i], so compare a[i-1].
  • @cache with deep recursion or list arguments: recursion-limit or unhashable-type errors.
Interview questions 2

Answer out loud first, then reveal.

How do you recognize a DP problem, and where do you start?Show answer

Signals: the question asks for a count, a min/max or feasibility, and a brute-force recursion revisits the same arguments. I write that recursion first, name the state as the parameters that change (index, remaining capacity), add @cache, and check that states × work per state fits the limits. If depth or memory is a problem, I convert to bottom-up and keep only the rows I need.

Top-down or bottom-up: which do you pick?Show answer

Top-down when the reachable states are sparse or the fill order is awkward: it mirrors the recurrence, so it's the fastest to get right. Bottom-up when I need every state anyway, the depth could pass Python's 1,000-frame limit, or I want to compress memory to one row. In an interview I often write top-down first, then offer the space-optimized bottom-up version.