Dynamic programming (DP) solves a problem by splitting it into smaller subproblems, solving each distinct subproblem once, and storing the answer so it can be reused. When the same subproblems appear again and again, that single idea turns exponential brute force into polynomial time. DP is less an algorithm than a way of thinking: define a state, relate it to smaller states, and fill in answers in the right order.
Think of it like
Counting on a whiteboard
A teacher writes 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 on the board and asks for the total. You count: eight. She adds one more + 1 and asks again. You answer "nine" instantly, because you remembered the previous total instead of recounting. That is dynamic programming: remember answers you have already worked out so you never redo the same work.
When does DP apply?
A problem is a good fit for dynamic programming when it has two properties. Miss either one and DP either does not help or gives wrong answers.
- Overlapping subproblems
- A naive recursive solution solves the same subproblem many times. Caching makes each one cost O(1) after the first time. Without overlap (as in Merge Sort, where halves are disjoint) caching buys nothing, and plain Divide & Conquer is enough.
- Optimal substructure
- An optimal answer can be assembled from optimal answers to subproblems. Shortest paths have it (every prefix of a shortest path is itself shortest). Longest simple paths in a general graph do not, which is why there is no polynomial DP for them.
- State
- The minimal set of parameters that identifies a subproblem, such as
i("the first i houses") or(i, w)("the first i items with capacity w"). - Transition (recurrence)
- The rule that computes a state from smaller states, usually by trying every option for one decision and taking the min, max, sum or logical OR.
- Base case
- The smallest states whose answers are known directly, such as
F(0) = 0or "an empty prefix has length 0".
Seeing the overlap: Fibonacci
The Fibonacci numbers are defined by a recurrence that translates directly into code. It is the smallest problem that shows why DP exists.
def fib(n: int) -> int:
if n < 2:
return n
return fib(n - 1) + fib(n - 2) # two calls, each spawning two more...Each call spawns two more, so the call tree roughly doubles at every level. Expand fib(6) and count how often each subproblem is evaluated. Use the visualization above to watch the same values being requested over and over.
| Subproblem | fib(6) | fib(5) | fib(4) | fib(3) | fib(2) | fib(1) | fib(0) |
|---|---|---|---|---|---|---|---|
| Times computed | 1 | 1 | 2 | 3 | 5 | 8 | 5 |
In general the naive version makes 2·F(n+1) − 1 calls, which grows like φⁿ ≈ 1.618ⁿ. Only n + 1 distinct subproblems exist, so almost all of that work is repetition.
Naive calls for fib(40)
331 million
2·F(41) − 1 = 331,160,281
Naive calls for fib(50)
40.7 billion
minutes of CPU time
Distinct subproblems for fib(50)
51
fib(0) … fib(50)
DP additions for fib(50)
49
one per state from 2 to 50
Two ways to remember: memoization and tabulation
Top-down: memoization
Keep the natural recursion, but check a cache before computing and store the result after. The recursion explores subproblems on demand, and each one is computed exactly once.
from functools import cache
@cache # same as a dict lookup before, dict store after
def fib(n: int) -> int:
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(90)) # 2880067194370816120, instantlyBottom-up: tabulation
Flip the direction. Allocate a table indexed by state, fill in the base cases, then fill the remaining cells in an order that guarantees every dependency is already computed. No recursion, no stack overflow risk, and usually smaller constant factors.
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| dp[i] | 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 |
| computed from | base | base | 1 + 0 | 1 + 1 | 2 + 1 | 3 + 2 | 5 + 3 | 8 + 5 | 13 + 8 |
Top-down (memoization)
- Write the recursion first, add a cache: easiest to get right
- Only visits states that are actually reachable
- Order of evaluation is automatic
- Recursion overhead, and deep recursion can overflow the stack (Python's default limit is 1000 frames)
- Hash-map caches are slower than arrays
Bottom-up (tabulation)
- Iterative loops over a dense array: fast and cache-friendly
- No stack depth limits
- You must work out a valid fill order yourself
- Computes every state, even unreachable ones
- Makes space optimization (rolling arrays) easy to see
Squeezing space with rolling arrays
Look at which cells a transition actually reads. Fibonacci's dp[i] only needs dp[i-1] and dp[i-2], so the rest of the table is dead weight. Keep just the last two values and the space drops from O(n) to O(1).
def fib(n: int) -> int:
if n < 2:
return n
prev, curr = 0, 1 # F(i-2), F(i-1)
for _ in range(2, n + 1):
prev, curr = curr, prev + curr
return currThe same trick generalizes. If row i of a 2D table depends only on row i-1, keep two rows (O(width) space instead of O(height × width)). Sometimes a single row suffices if you iterate in the right direction, which is the key idea behind the 1D Knapsack Problems.
| Version | Time | Extra space | Comment |
|---|---|---|---|
| Naive recursion | O(φⁿ) | O(n) stack | Exponential: unusable beyond n ≈ 40 |
| Memoization | O(n) | O(n) cache + O(n) stack | Natural to write, recursion depth n |
| Tabulation | O(n) | O(n) table | Iterative, no recursion |
| Rolling variables | O(n) | O(1) | Keeps only the last two values |
| Matrix power | O(log n) | O(1) | Raise [[1, 1], [1, 0]] to the nth power by squaring |
A five-step framework for any DP problem
Most people get stuck on DP because they try to jump straight to code. Instead, answer these five questions in order, out loud if you are in an interview. Every worked example below follows them.
- 1
Define the state in words
Write one sentence: "
dp[i]is the maximum loot from the firstihouses." If you cannot say what a cell means, you cannot write its recurrence. Choose the fewest parameters that make the future independent of how you got here. - 2
Find the recurrence from the last decision
Ask: what is the last choice an optimal solution makes? (Did I rob the last house or not? Was my last step 1 stair or 2?) Each option leads to a smaller state. Combine the options with min, max, sum or OR.
- 3
Pin down the base cases
Which states can be answered without the recurrence? Empty prefixes, zero capacity, the first one or two elements. Off-by-one errors live here, so test the smallest inputs by hand.
- 4
Choose the computation order and locate the answer
Fill states so that every dependency is computed first (usually increasing
i). Decide which cell holds the final answer: the last cell, or the max over all cells. - 5
Optimize space and reconstruct if needed
If a state only reads the previous one or two layers, roll the array. If the actual solution is required, keep the table (or parent pointers) and walk backward from the answer.
| Problem | State | # states | Work per state | Total time |
|---|---|---|---|---|
| Fibonacci, climbing stairs | dp[i] | n | O(1) | O(n) |
| House robber | dp[i] | n | O(1): rob or skip | O(n) |
| 0/1 knapsack | dp[i][w] | n·W | O(1): take or leave | O(n·W) |
| Longest common subsequence | dp[i][j] | m·n | O(1) | O(m·n) |
| Longest increasing subsequence | dp[i] | n | O(n): scan all j < i | O(n²) |
| Matrix chain multiplication | dp[i][j] | n² | O(n): try every split | O(n³) |
| Traveling salesman (Held-Karp) | dp[mask][v] | 2ⁿ·n | O(n): next city | O(n²·2ⁿ) |
Worked example: climbing stairs
You climb a staircase of n steps, taking either 1 or 2 steps at a time. How many distinct sequences of moves reach the top?
- 1
State
ways(i)= the number of distinct move sequences that end exactly on stepi. - 2
Last decision
The final move onto step
iwas either a 1-step (fromi-1) or a 2-step (fromi-2). These are disjoint cases, so add them. - 3
Base cases
ways(0) = 1(one way to stand at the bottom: do nothing) andways(1) = 1. - 4
Order and answer
Increasing
i; the answer isways(n). Only the previous two values are needed, so O(1) space.
| n | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| ways(n) | 1 | 2 | 3 | 5 | 8 | 13 |
| example sequences | 1 | 1+1, 2 | 1+1+1, 1+2, 2+1 | … | … | … |
Worked example: house robber
Houses along a street hold nums[i] dollars. Robbing two adjacent houses triggers an alarm. What is the most you can steal?
Greedy ideas fail. "Take the richest house first" on [3, 4, 3] takes 4 and blocks both neighbors, but 3 + 3 = 6 is better. "Take every other house" on [2, 1, 1, 2] gives 3, but houses 0 and 3 give 4. We need to consider both options at every house, which is exactly what DP does efficiently.
- 1
State
dp[i]= the maximum loot using only the firstihouses (nums[0..i-1]). - 2
Last decision
Either skip house
i-1(lootdp[i-1]), or rob it, which forbids housei-2(lootdp[i-2] + nums[i-1]). Take the max. - 3
Base cases
dp[0] = 0(no houses),dp[1] = nums[0]. - 4
Order and answer
Increasing
i; the answer isdp[n]. Two rolling variables give O(1) space.
| i | house value nums[i-1] | skip: dp[i-1] | rob: dp[i-2] + value | dp[i] |
|---|---|---|---|---|
| 0 | 0 | |||
| 1 | 2 | 0 | 0 + 2 = 2 | 2 |
| 2 | 7 | 2 | 0 + 7 = 7 | 7 |
| 3 | 9 | 7 | 2 + 9 = 11 | 11 |
| 4 | 3 | 11 | 7 + 3 = 10 | 11 |
| 5 | 1 | 11 | 11 + 1 = 12 | 12 |
Reconstructing the choice. Walk backward from i = n. If dp[i] ≠ dp[i-1], house i-1 must have been robbed, so record it and jump to i-2; otherwise move to i-1. Here: dp[5] ≠ dp[4] (rob house 4), dp[3] ≠ dp[2] (rob house 2), dp[1] ≠ dp[0] (rob house 0). Houses {0, 2, 4} give 2 + 9 + 1 = 12.
Worked example: min cost climbing stairs
Step i has a cost cost[i] that you pay when you step off it, moving up 1 or 2 steps. You may start on step 0 or step 1, and you want to reach the top, which is the position just past the last step (index n). What is the minimum total cost?
- 1
State
dp[i]= the minimum cost to stand on positioni(the top isi = n). - 2
Last decision
You arrived from
i-1(payingcost[i-1]) or fromi-2(payingcost[i-2]). - 3
Base cases
dp[0] = dp[1] = 0, because you may start on either for free. - 4
Order and answer
Increasing
i; answerdp[n]; O(1) space with two variables.
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 (top) |
|---|---|---|---|---|---|---|---|---|---|---|---|
| cost[i] | 1 | 100 | 1 | 1 | 1 | 100 | 1 | 1 | 100 | 1 | |
| dp[i] | 0 | 0 | 1 | 2 | 2 | 3 | 3 | 4 | 4 | 5 | 6 |
Recognizing DP problems
- The question asks for a count ("how many ways"), an optimum ("minimum cost", "maximum profit", "longest") or feasibility ("is it possible").
- You make a sequence of decisions, and each decision changes what is possible later.
- A brute-force recursion exists but is exponential, and its arguments take few distinct values.
- Input sizes hint at the intended complexity: n ≤ 20 suggests bitmasks, n ≤ 500 suggests O(n³), n ≤ 5000 suggests O(n²), n ≤ 10⁵ suggests O(n) or O(n log n).
- If the problem asks for all solutions (every permutation, every valid board), DP rarely helps: you need to enumerate them with Backtracking.
| Family | Typical state | Where to learn it |
|---|---|---|
| Linear sequences | dp[i] over a prefix | This page |
| Capacity and choice | dp[i][capacity] | Knapsack Problems |
| Two sequences | dp[i][j] over two prefixes | LCS & Edit Distance |
| Subsequences | dp[i] = best ending at i | Longest Increasing Subsequence |
| Grids | dp[r][c] | Grid & Path DP |
| Intervals, subsets, trees, modes | dp[i][j], dp[mask], dp[node] | Advanced DP Patterns |
Complexity
| Approach | Time | Space | Notes |
|---|---|---|---|
| Naive recursion (Fibonacci) | O(φⁿ) | O(n) | φ ≈ 1.618; recursion stack depth n |
| Memoization | O(n) | O(n) | Cache plus recursion stack |
| Tabulation | O(n) | O(n) | One array cell per state |
| Rolling variables | O(n) | O(1) | Only the last two states are kept |
| House robber / min cost stairs | O(n) | O(1) | O(n) if you keep the table to reconstruct choices |
General rule: time = number of states × work per transition; space = number of states, often reducible to the size of one layer.
Implementation
The same recurrence written three ways (plus the naive baseline). Results fit in a 64-bit integer up to F(92).
def fib_naive(n: int) -> int:
"""O(phi^n) time: recomputes the same subproblems exponentially often."""
if n < 2:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
def fib_memo(n: int, memo: dict[int, int] | None = None) -> int:
"""Top-down: O(n) time, O(n) cache + O(n) recursion depth."""
if memo is None:
memo = {}
if n < 2:
return n
if n not in memo:
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
def fib_table(n: int) -> int:
"""Bottom-up: O(n) time, O(n) table, no recursion."""
if n < 2:
return n
dp = [0] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
def fib(n: int) -> int:
"""Rolling variables: O(n) time, O(1) space."""
if n < 2:
return n
prev, curr = 0, 1 # F(i-2), F(i-1)
for _ in range(2, n + 1):
prev, curr = curr, prev + curr
return currKey takeaways
- DP applies when a problem has overlapping subproblems and optimal substructure; it solves each distinct subproblem once.
- Memoization (top-down) adds a cache to the recursion; tabulation (bottom-up) fills a table in dependency order. Same complexity, different trade-offs.
- Follow the framework: state in words, recurrence from the last decision, base cases, computation order, then space optimization.
- Time = number of states × work per transition. Count both explicitly before coding.
- If a state only reads the previous one or two layers, a rolling array cuts space by a whole dimension, at the cost of losing reconstruction.
Common pitfalls
- Defining the state vaguely ("dp[i] is the answer for i") and then writing a recurrence that mixes two different meanings.
- Wrong base cases, especially
ways(0): there is exactly one way to make zero progress (do nothing), not zero ways. - Filling the table in an order where a cell reads a neighbor that has not been computed yet.
- Using memoization with mutable or unhashable state (lists as keys), or sharing a cache between unrelated test cases.
- Applying a rolling array and then trying to reconstruct the chosen elements from it.
Interview tips
- Say the state definition out loud as a full sentence before writing any recurrence; it is the most common thing interviewers probe.
- Start from the brute-force recursion, point out the repeated subproblems, then add memoization. This shows you understand why DP works.
- Always state the complexity as states × transition cost, then offer the space optimization as a follow-up.
- Test your recurrence on the smallest inputs (n = 0, 1, 2) before trusting it.
Real-world applications
- Resource allocation and budgeting problems (which projects to fund under a cost limit).
- Bioinformatics sequence alignment and text diffing, built on two-sequence DP.
- Speech recognition and part-of-speech tagging with the Viterbi algorithm (DP over a hidden Markov model).
- Reinforcement learning: value iteration and the Bellman equation are dynamic programming over states.
- Compilers: optimal instruction selection and register allocation on expression trees.
Practice problems
Test yourself
Which pair of properties makes a problem a good candidate for dynamic programming?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.