AlgoViz

Dynamic programming: core concepts

medium 18 min

Dynamic programming solves a problem by breaking it into smaller subproblems, solving each distinct subproblem once and storing the answer.

Chapter mnemonic

Four dynamic programming decisions

Label the jars. Fill the starters. Follow the recipe. Cook in order.

What does the recipe tell you, and why cook some jars first?

The recurrence combines dependency states. The computation order makes those answers available first.

Video lesson · Chapter 1 of 5

Why keep a notebook?

0:00 / 4:19

Dynamic programming in 90 seconds

1:27Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Spot the repeats. Draw the brute-force recursion and look for the same arguments in different branches

Understand it

Start here

What dynamic programming is

Dynamic programming (DP) breaks a problem into smaller subproblems, solves each distinct subproblem once, and stores the answer so it is never computed again. It turns many exponential brute-force recursions into polynomial ones, often O(n)O(n) or O(n2)O(n^2).

  • Break it down

    Express the answer to a big question in terms of answers to smaller questions of the same kind.

  • Solve each once

    The same small questions come up many times. Work each out a single time.

  • Write it down

    Store answers in a memo or a table, so the second time costs one lookup.

Property 1

Overlapping subproblems

A problem has overlapping subproblems when a plain recursion solves the same smaller problem many times. Computing fib(5) calls fib(4) and fib(3), but fib(4) also calls fib(3). In the end fib(3) is computed twice, fib(2) three times and fib(1) five times: 15 calls for only 6 distinct questions.

fib(5): a tree of 15 calls is a graph of 6 subproblems

Merge the repeated calls and the call tree collapses into a small graph: one node per distinct subproblem, one arrow per dependency. DP does the work of this graph, not of the tree.
nNaive callsMemoised callsSpeed-up
51591.7×
625112.3×
741133.2×
867154.5×
9109176.4×
10177199.3×
Naive fib(n) makes 2F(n+1)−12F(n+1) - 1 calls; memoised makes 2n−12n - 1. Each +1 to nn multiplies the first by about 1.6 and adds 2 to the second.

Property 2

Optimal substructure

A problem has optimal substructure when the best answer can be built from best answers to its subproblems. To reach the top of a staircase as cheaply as possible, you must first reach the step before it (or the one before that) as cheaply as possible. Any cheaper way to that earlier step would make the whole route cheaper.

Min cost climbing as a recurrence

dp[i]=min⁡(dp[i−1]+cost[i−1],  dp[i−2]+cost[i−2]),dp[0]=dp[1]=0\text{dp}[i] = \min\big(\text{dp}[i-1] + \text{cost}[i-1],\; \text{dp}[i-2] + \text{cost}[i-2]\big), \qquad \text{dp}[0] = \text{dp}[1] = 0
The best cost to stand on step ii uses the best costs to stand on steps i−1i - 1 and i−2i - 2. Counting problems work the same way with ++ instead of min⁡\min: F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2).

The recipe

State, transition, base case, order

Four decisions make every DP

  1. 1

    State

    What one subproblem means, in words. dp[i] = the cheapest cost to stand on step ii. Include every variable the answer depends on, and nothing more.

  2. 2

    Transition

    How a state's answer comes from smaller states, usually with ++, min⁡\min or max⁡\max over the choices for the last move.

  3. 3

    Base cases

    The smallest states whose answers you know without recursion, such as dp[0] = dp[1] = 0.

  4. 4

    Order

    An evaluation order in which every state's inputs are ready first. Top-down gets it free from recursion; bottom-up needs you to pick the loop direction.

From brute force to a finished DP

The brute-force recursion already contains the state (its parameters), the transition (its recursive line) and the base cases (its stopping test). DP only adds storage and an order.

Worked example

Unique paths on a grid

Count the paths from the top-left to the bottom-right of a grid moving only right or down. State: dp[r][c] = paths into cell (r, c). Transition: the last move came from above or from the left. Base cases: the top row and left column have exactly one path each. Order: row by row, left to right. The full problem is Unique paths.

The grid recurrence

dp[r][c]=dp[r−1][c]+dp[r][c−1],dp[0][c]=dp[r][0]=1\text{dp}[r][c] = \text{dp}[r-1][c] + \text{dp}[r][c-1], \qquad \text{dp}[0][c] = \text{dp}[r][0] = 1
For a 3 × 4 grid the corner is 10, which matches (3+4−23−1)=(52)=10\binom{3 + 4 - 2}{3 - 1} = \binom{5}{2} = 10: choose which 2 of the 5 moves go down.
c0c1c2c3
r01111
r11234
r213610
Each cell is the sum of the cell above and the cell to its left. 12 states, one addition each.
Python
def unique_paths(rows, cols):    dp = [[0] * cols for _ in range(rows)]    for c in range(cols):        dp[0][c] = 1                      # top row: only moves right    for r in range(rows):        dp[r][0] = 1                      # left column: only moves down    for r in range(1, rows):              # row by row, left to right        for c in range(1, cols):            dp[r][c] = dp[r - 1][c] + dp[r][c - 1]    return dp[rows - 1][cols - 1]print(unique_paths(3, 4))    # 10print(unique_paths(10, 10))  # 48620
Bottom-up table for unique paths.
Edit and run it in your browser

Approach 1

Top-down: memoisation

Memoisation keeps the recursion exactly as written and adds a cache. Before computing a state, look it up; after computing it, store it. It only visits states actually reachable from the starting question, and the recursion takes care of the order for you.

One memoised call

Each state reaches the bottom box at most once, so the total work is the number of states times the work inside one call.
Python
from functools import cachedef min_cost_climb(cost):    n = len(cost)    @cache    def best(i):                     # cheapest cost to stand on step i        if i <= 1:            return 0                 # start on step 0 or 1 for free        return min(best(i - 1) + cost[i - 1], best(i - 2) + cost[i - 2])    return best(n)                   # n is the topprint(min_cost_climb([10, 15, 20]))                          # 15print(min_cost_climb([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]))  # 6
Min cost climbing, top-down. @cache does the lookup and the store.
Edit and run it in your browser

Approach 2

Bottom-up: tabulation

Tabulation turns the recursion inside out. Allocate a table, write the base cases, then loop over the states in an order where every input is already filled. No recursion means no stack and no depth limit, and the loop usually runs faster than the equivalent calls.

Tabulation pipeline
  1. 1AllocateOne cell per state, e.g. n + 1 cells
  2. 2SeedWrite the base cases
  3. 3FillLoop in dependency order, apply the transition
  4. 4ReadReturn the cell for the original question
Naive recursionMemoisationTabulation
ApproachRecursiveRecursive + cacheIterative
DirectionTop-downTop-downBottom-up
Time (Fibonacci)O(2n)O(2^n)O(n)O(n)O(n)O(n)
SpaceO(n)O(n) stackO(n)O(n) memo + stackO(n)O(n) table, often O(1)O(1)
States computedMany, repeatedlyOnly reachable onesAll of them
Ease of writingEasyEasyModerate: pick the order
Stack overflow riskHighMediumNone
Both DP styles do the same work. Choose memoisation to get going fast or when few states are reachable; choose tabulation for deep inputs and space optimisation.

Fill order follows the arrows

Every arrow goes right or down, so row by row, left to right, is a valid order. In general any topological order of the dependency graph works.

Space

Rolling variables

Look at which cells the transition reads. Min cost climbing reads only dp[i - 1] and dp[i - 2], so everything further left is dead weight. Keep a window of two variables and slide it each step: the same answer in O(1)O(1) space.

Space depends on the window, not the table

dp[i]=f(dp[i−1],…,dp[i−k])  ⟹  space O(k) instead of O(n)\text{dp}[i] = f(\text{dp}[i-1], \dots, \text{dp}[i-k]) \;\Longrightarrow\; \text{space } O(k) \text{ instead of } O(n)
Fibonacci and climbing stairs have k=2k = 2. A 2D table whose rows read only the row above shrinks from O(rows⋅cols)O(\text{rows} \cdot \text{cols}) to one row, O(cols)O(\text{cols}).
Python
def min_cost_climb(cost):    prev2, prev1 = 0, 0                    # dp[0], dp[1]    for i in range(2, len(cost) + 1):        cur = min(prev1 + cost[i - 1], prev2 + cost[i - 2])        prev2, prev1 = prev1, cur          # slide the window    return prev1def unique_paths(rows, cols):    row = [1] * cols                       # the top row    for _ in range(1, rows):        for c in range(1, cols):            row[c] += row[c - 1]           # above (old row[c]) + left (new row[c-1])    return row[-1]print(min_cost_climb([2, 7, 3, 4, 9, 1]))  # 10print(unique_paths(3, 4))                  # 10
The same two problems with a rolling window.
Edit and run it in your browser

Complexity

Time = states × transition cost

Every DP does the same thing: compute each state once. So the running time is the number of distinct states multiplied by the work one transition does, and the space is the number of states you keep.

The counting rule

T=# states⏟distinct subproblems×cost per state⏟choices tried,S=# states keptT = \underbrace{\#\,\text{states}}_{\text{distinct subproblems}} \times \underbrace{\text{cost per state}}_{\text{choices tried}}, \qquad S = \#\,\text{states kept}
Lookups in a memo or table are O(1)O(1), so a state's cost is the number of smaller states it combines.
ProblemStatesWork per stateTimeSpace after rolling
Fibonacci, climbing stairsnnO(1)O(1)O(n)O(n)O(1)O(1)
Min cost climbing, house robbernnO(1)O(1)O(n)O(n)O(1)O(1)
Unique paths, m×nm \times n gridmnmnO(1)O(1)O(mn)O(mn)O(n)O(n)
0/1 knapsack, capacity WWnWnWO(1)O(1)O(nW)O(nW)O(W)O(W)
Longest increasing subsequencennO(n)O(n)O(n2)O(n^2)O(n)O(n)
Coin change, kk coins, amount AAAAO(k)O(k)O(kA)O(kA)O(A)O(A)
The same rule explains naive Fibonacci: without storage the 'states' are the 2F(n+1)−12F(n+1) - 1 calls of the tree, not the n+1n + 1 distinct values.

Example: longest increasing subsequence

dp[i]=1+max⁡j<i,  aj<aidp[j]⇒∑i=1nO(i)=O ⁣(n(n+1)2)=O(n2)\text{dp}[i] = 1 + \max_{j < i,\; a_j < a_i} \text{dp}[j] \quad\Rightarrow\quad \sum_{i=1}^{n} O(i) = O\!\left(\frac{n(n+1)}{2}\right) = O(n^2)
nn states, but state ii looks at up to ii earlier states, so the work adds up to a triangle.

Pattern spotting

How to recognise a DP problem

Is this a DP problem?

Greedy commits to the locally best choice and never looks back; DP compares every choice through the stored sub-answers. Coin change with coins 1, 3, 4 and amount 6 breaks greedy (4 + 1 + 1) but not DP (3 + 3).
  • Count the ways

    How many paths, decodings or arrangements? Sum over the last move.

  • Best value

    Minimum cost, maximum profit, longest or shortest something. Take min or max over the last choice.

  • Is it possible?

    Can you reach the end, make the amount, split the set? OR over the choices.

  • Choices shape the future

    Taking an item, robbing a house or cutting a rod changes what is allowed next.

DP fits

  • Fibonacci-style sequences, climbing stairs, house robber
  • Shortest paths with no negative cycles, grid paths
  • Knapsack, coin change, subset sum
  • Longest common subsequence, edit distance
  • Matrix chain multiplication, interval problems

DP does not help

  • Subproblems never repeat (merge sort, factorial)
  • A greedy choice is provably optimal (activity selection)
  • A simple loop already works in one pass
  • No optimal substructure (longest simple path)
  • The state space is too large to store

Where next

The classic one-dimensional problems

These four problems use the recipe on this page with almost no extra machinery. Work through them in this order.

  • Climbing stairs

    Steps of 1 or 2: ways(n) = ways(n - 1) + ways(n - 2). Fibonacci in disguise.

  • Min cost climbing

    The same staircase, with min⁡\min and a cost per step. Rolling variables give O(1)O(1) space.

  • House robber

    Rob house ii plus the best up to i−2i - 2, or skip it and keep the best up to i−1i - 1.

  • Unique paths

    The first 2D table: paths from above plus paths from the left.

Do

  • Write the state as one precise sentence before coding.
  • Check base cases like n=0n = 0 and n=1n = 1 by hand.
  • Use ∞\infty as the starting value for minimums and −∞-\infty for maximums.
  • Write the full table first; optimise space last.

Don't

  • Leave a variable the answer depends on out of the state.
  • Fill cells before their inputs are ready.
  • Use memo={} as a default argument.
  • Assume a greedy choice works without a proof.

Recap

Key takeaways

Key points

  • DP solves each distinct subproblem once and stores its answer.
  • It needs overlapping subproblems and optimal substructure. Without overlap it is just divide and conquer.
  • Every DP is four decisions: state, transition, base cases and evaluation order.
  • Top-down memoisation keeps the recursion and adds a cache; bottom-up tabulation fills a table with loops.
  • Time is states times work per state; space is the states you keep.
  • If a transition reads only the last k states, keep k variables: O(1) space for Fibonacci-style problems.
  • Signals: count the ways, min or max, is it possible, and choices that shape what comes next.

Sources