Dynamic programming: core concepts
medium 18 minDynamic 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?
Dynamic programming in 90 seconds
1:27Reel
How it works
Step through the idea, or press Play.
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 or .
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
| n | Naive calls | Memoised calls | Speed-up |
|---|---|---|---|
| 5 | 15 | 9 | 1.7× |
| 6 | 25 | 11 | 2.3× |
| 7 | 41 | 13 | 3.2× |
| 8 | 67 | 15 | 4.5× |
| 9 | 109 | 17 | 6.4× |
| 10 | 177 | 19 | 9.3× |
fib(n) makes calls; memoised makes . Each +1 to 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
The recipe
State, transition, base case, order
Four decisions make every DP
- 1
State
What one subproblem means, in words.
dp[i]= the cheapest cost to stand on step . Include every variable the answer depends on, and nothing more. - 2
Transition
How a state's answer comes from smaller states, usually with , or over the choices for the last move.
- 3
Base cases
The smallest states whose answers you know without recursion, such as
dp[0] = dp[1] = 0. - 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
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
| c0 | c1 | c2 | c3 | |
|---|---|---|---|---|
| r0 | 1 | 1 | 1 | 1 |
| r1 | 1 | 2 | 3 | 4 |
| r2 | 1 | 3 | 6 | 10 |
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)) # 48620Approach 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
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@cache does the lookup and the store.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.
- 1AllocateOne cell per state, e.g. n + 1 cells
- 2SeedWrite the base cases
- 3FillLoop in dependency order, apply the transition
- 4ReadReturn the cell for the original question
| Naive recursion | Memoisation | Tabulation | |
|---|---|---|---|
| Approach | Recursive | Recursive + cache | Iterative |
| Direction | Top-down | Top-down | Bottom-up |
| Time (Fibonacci) | |||
| Space | stack | memo + stack | table, often |
| States computed | Many, repeatedly | Only reachable ones | All of them |
| Ease of writing | Easy | Easy | Moderate: pick the order |
| Stack overflow risk | High | Medium | None |
Fill order follows the arrows
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 space.
Space depends on the window, not the table
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)) # 10Complexity
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
| Problem | States | Work per state | Time | Space after rolling |
|---|---|---|---|---|
| Fibonacci, climbing stairs | ||||
| Min cost climbing, house robber | ||||
| Unique paths, grid | ||||
| 0/1 knapsack, capacity | ||||
| Longest increasing subsequence | ||||
| Coin change, coins, amount |
Example: longest increasing subsequence
Pattern spotting
How to recognise a DP problem
Is this a DP problem?
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.
Steps of 1 or 2:
ways(n) = ways(n - 1) + ways(n - 2). Fibonacci in disguise.The same staircase, with and a cost per step. Rolling variables give space.
Rob house plus the best up to , or skip it and keep the best up to .
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 and by hand.
- Use as the starting value for minimums and 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.