Dynamic Programming
Solve each overlapping subproblem once. A step-by-step framework — state, transition, base case, order — with memoization and tabulation.
Dynamic programming (DP) solves problems by breaking them into overlapping subproblems, solving each once, and storing the answers. It turns exponential brute force into polynomial time.
A problem is a DP candidate when it has:
- Optimal substructure — the optimal answer is built from optimal answers to subproblems.
- Overlapping subproblems — the same subproblems are needed again and again.
The framework
- Define the state. What does
dp[i](ordp[i][j]) mean, in words? This is the hardest and most important step. - Write the transition. How is
dp[i]computed from smaller states? - Set base cases. The smallest states you know directly.
- Choose an order. Compute states so dependencies are ready (or recurse with memoization).
- Locate the answer (
dp[n],max(dp), …) and optimise space if only recent rows are needed.
Worked example: climbing stairs
You can climb 1 or 2 steps at a time. How many distinct ways to reach step n?
- State:
ways(i)= number of ways to reach step i. - Transition: the last move was a 1-step from i−1 or a 2-step from i−2, so
ways(i) = ways(i−1) + ways(i−2). - Base:
ways(0) = 1,ways(1) = 1.
Top-down: memoization
Write the natural recursion, then cache results.
Bottom-up: tabulation
Fill a table from the base cases upward — no recursion, and you can often keep only the last few values.
// Top-down (memoized recursion)
int ways(int i, int[] memo) {
if (i <= 1) return 1;
if (memo[i] != 0) return memo[i];
return memo[i] = ways(i - 1, memo) + ways(i - 2, memo);
}
// Bottom-up (tabulation)
int climbStairs(int n) {
int[] dp = new int[n + 1];
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2];
return dp[n];
}
// Bottom-up with O(1) space
int climbStairsO1(int n) {
int prev = 1, cur = 1;
for (int i = 2; i <= n; i++) { int next = prev + cur; prev = cur; cur = next; }
return cur;
}from functools import cache
@cache # top-down
def ways(i: int) -> int:
return 1 if i <= 1 else ways(i - 1) + ways(i - 2)
def climb_stairs(n: int) -> int: # bottom-up, O(1) space
prev, cur = 1, 1
for _ in range(2, n + 1):
prev, cur = cur, prev + cur
return curfunction climbStairs(n: number): number { // bottom-up, O(1) space
let prev = 1, cur = 1;
for (let i = 2; i <= n; i++) [prev, cur] = [cur, prev + cur];
return cur;
}- Natural: write the recursion, add a cache
- Only computes states actually needed
- Recursion overhead; stack depth limits
- Easier to derive first
- Iterative loops in dependency order
- Computes every state
- No recursion; usually faster
- Enables rolling-array space optimisation
Worked example: house robber
Houses in a row hold a[i] money; you can't rob two adjacent houses. Maximise loot.
- State:
dp[i]= best loot from the first i houses. - Transition: skip house i−1 →
dp[i−1]; or rob it →dp[i−2] + a[i−1]. Take the max.
int rob(int[] a) {
int prev2 = 0, prev1 = 0; // dp[i-2], dp[i-1]
for (int x : a) {
int cur = Math.max(prev1, prev2 + x);
prev2 = prev1;
prev1 = cur;
}
return prev1;
}def rob(a):
prev2 = prev1 = 0
for x in a:
prev2, prev1 = prev1, max(prev1, prev2 + x)
return prev1function rob(a: number[]): number {
let prev2 = 0, prev1 = 0;
for (const x of a) [prev2, prev1] = [prev1, Math.max(prev1, prev2 + x)];
return prev1;
}Worked example: unique paths in a grid (2D DP)
A robot moves only right or down in an m × n grid. dp[r][c] = dp[r−1][c] + dp[r][c−1], with the first row and column all 1.
Recognising DP problems
Strong signals in the problem statement:
- "Count the number of ways to …"
- "Minimum / maximum cost, profit, length …"
- "Is it possible to reach / partition / form …"
- Choices at each step, where a greedy choice can go wrong.
- Constraints like n ≤ 1000 or n ≤ 5000 (O(n²) DP) or a small "capacity" dimension.
Common DP families
| Family | State | Examples | Lesson |
|---|---|---|---|
| 1D linear | dp[i] | stairs, house robber, decode ways, LIS | DP classics |
| Two sequences | dp[i][j] over prefixes | LCS, edit distance | DP on sequences |
| Knapsack | dp[i][capacity] | 0/1 knapsack, subset sum, coin change | Knapsack DP |
| Grid | dp[r][c] | unique paths, min path sum | DP on grids & intervals |
| Interval | dp[l][r] | matrix chain, burst balloons, palindromes | DP on grids & intervals |
| Bitmask | dp[mask] | TSP on ≤ 20 cities, assignments | DP classics |
| Tree | dp[node][state] | house robber III, max independent set | Tree DFS |
- DP = recursion + caching for overlapping subproblems with optimal substructure.
- Always define the state in words first; then transition, base cases, order, answer.
- Top-down memoization is easiest to derive; bottom-up tabulation is faster and space-optimisable.
- Complexity = (number of states) × (work per transition).
QHow do you derive the time complexity of a DP solution?easy
Multiply the number of distinct states by the work to compute each one. Edit distance has (m+1)(n+1) states with O(1) transitions → O(mn). LIS with dp[i] = max over j < i has n states with O(n) transitions → O(n²).
QDecode ways: how many ways can a digit string be decoded with A=1 … Z=26?medium
dp[i] = ways to decode the first i characters. Add dp[i−1] if s[i−1] is not '0'; add dp[i−2] if the two-digit number s[i−2..i−1] is between 10 and 26. Base dp[0] = 1. O(n) time, O(1) space with two variables.
QHow do you reconstruct the actual solution, not just its value?medium
Either store the choice made at each state (a "parent" table) or, after filling the table, walk backwards from the answer state, at each step checking which transition produced its value.