Dynamic Programming · Lesson
Dynamic programming, explained: the method, the templates and every pattern
Learn dynamic programming step by step: state, recurrence, base case and order, then 1D, grid, knapsack, string and interval DP in Java, Python, C++ and JS.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
What dynamic programming is
Dynamic programming (DP) is recursion that remembers. Many recursive solutions solve the same smaller problem again and again: fib(5) calls fib(3) twice, fib(2) three times, and the work grows exponentially. DP solves each smaller problem once, stores the answer and reuses it.
It works when two things are true. The problem splits into smaller problems of the same shape (the best answer for n is built from best answers for smaller inputs), and those smaller problems overlap, so remembering them saves work. Typical asks: count the ways, find the minimum or maximum, or say whether something is possible.
The method: five questions
Answer these in order, and write the answers down before you code. Most DP bugs come from skipping step 1.
- State: what does
dp[i](ordp[i][j]) mean, in one sentence? For example, "dp[i]= number of ways to reach stepi". The state must hold everything the future depends on. - Choices: what can you do at this state? Take or skip an item, step 1 or 2, match or skip a character.
- Recurrence: combine the choices. Count problems add them; optimisation problems take the min or max.
ways(i) = ways(i - 1) + ways(i - 2). - Base case: the smallest states you know without thinking, such as
dp[0] = 1(one way to do nothing) or an empty string. - Order: fill states so that everything a state needs is already computed. Usually small to big; sometimes right to left, or short intervals before long ones.
The cost is then simple: number of states × work per state.
Memo, table or a few variables
- Top-down (memoisation): write the plain recursion, then cache each result in a map or array. Easiest to get right, and it only visits states you actually need. The cost is recursion depth (stack overflow on large inputs).
- Bottom-up (tabulation): a loop fills the
dparray in the right order. No recursion, usually faster, and it makes the next step possible. - Space optimised: if row
ionly reads rowi - 1(or the last two values), keep just those. Climbing Stairs drops from an O(n) array to two variables; a grid DP drops to one row.
A good habit: think top-down (it is the natural recursion), then convert to bottom-up once the recurrence is clear, and shrink the space last.
What it costs
| Operation | Time | Space |
|---|---|---|
| 1D DP, O(1) choices per state (stairs, robber) | O(n) | O(n), or O(1) with variables |
| Grid DP on m × n | O(m·n) | O(m·n), or O(n) with one row |
| Two strings of length n and m (LCS, edit distance) | O(n·m) | O(n·m), or O(m) with two rows |
| 0/1 or unbounded knapsack, n items, capacity W | O(n·W) | O(W) |
| Interval DP on n items | O(n³) | O(n²) |
| Bitmask DP over n items | O(2ⁿ·n) | O(2ⁿ) |
Built into your language
int[] dp = new int[n + 1]; // bottom-up table, starts at 0
Arrays.fill(dp, Integer.MAX_VALUE); // "not reached yet" for min problems
int[][] memo = new int[n][m];
for (int[] row : memo) Arrays.fill(row, -1); // -1 = not computed (top-down)
Map<String, Integer> cache = new HashMap<>(); // memo with a composite key
cache.put(i + "," + j, 5);
cache.getOrDefault(i + "," + j, -1); dp = [0] * (n + 1) # bottom-up table
grid = [[0] * m for _ in range(n)] # NOT [[0] * m] * n: that shares one row
from functools import cache # top-down memoisation in one line
@cache
def ways(i):
return 1 if i <= 1 else ways(i - 1) + ways(i - 2)
import sys; sys.setrecursionlimit(10**6) # deep recursion needs a higher limit vector<int> dp(n + 1, 0); // bottom-up table
vector<vector<int>> memo(n, vector<int>(m, -1)); // -1 = not computed
vector<long long> big(n + 1, LLONG_MAX / 2); // safe "infinity" you can add to
const int MOD = 1e9 + 7; // counts are usually taken mod 1e9 + 7 const dp = new Array(n + 1).fill(0); // bottom-up table
const memo = Array.from({ length: n }, () => new Array(m).fill(-1)); // a separate array per row
const cache = new Map(); // memo with a composite key
cache.set(i + "," + j, 5);
cache.has(i + "," + j);
// counts mod 1e9 + 7: a * b can pass 2^53, use BigInt for the product Mistakes everyone makes
- Writing code before defining the state. If you cannot say what
dp[i]means in one sentence, the recurrence will be wrong. - Wrong base case for empty input: there is usually one way to make sum 0 or match two empty strings, not zero.
- Filling the table in the wrong order, so a state reads a neighbour that has not been computed yet.
- A state that forgets something the future depends on (the last colour used, whether you hold a stock). Add it as another dimension.
- Overflow in counts: take the answer mod 1e9 + 7 at every addition, and use 64-bit integers for products.
The 12 patterns, in order
Each one: the idea and template, its variations with a worked example, then problems for you to solve.
- 1 1D DP: the answer at i from earlier answers The state is one index:
dp[i]is the answer for the firstiitems (or for ending at itemi). Each state looks back at a few earlier states, or at all of them, and combines them. 6 variations · 21 problems - 2 Pick or not pick: House Robber At each item you either take it (and must skip its neighbour) or leave it.
best(i) = max(best(i - 1), best(i - 2) + nums[i]), and two variables are enough. 2 variations · 2 problems - 3 2D DP: grids and two-index states The state has two numbers: a cell
(r, c)in a grid, or an index plus a budget (dice used and sum, moves and eggs). Each cell is built from neighbours that were filled earlier, and often one row of memory is enough. 3 variations · 13 problems - 4 Row by row: the best of the last row Fill the table one row at a time; each cell takes the best of a few cells in the row above. There is no single end cell, so the answer is the max or min over the whole last row. 2 variations · 3 problems
- 5 Squares: the largest square ending at each cell
dp[r][c]= side of the largest all-ones square whose bottom-right corner is(r, c). It is one more than the smallest of its three neighbours: up, left and up-left. 2 variations · 3 problems - 6 State machine DP: every Buy and Sell Stock problem Each day you are in a state: holding a share or not (plus how many trades are left, or a cooldown). Write how each state is reached from yesterday's states, and keep one variable per state. 5 variations · 6 problems
- 7 Knapsack: choose items under a capacity
dp[c]= the best value (or number of ways) using capacityc. Loop capacity right to left when each item may be used once (0/1), and left to right when items can be reused (unbounded). 4 variations · 11 problems - 8 String DP: two indexes, one per string
dp[i][j]describes the firsticharacters of one string and the firstjof the other (or the substrings[i..j]). If the last characters match, move both; if not, try each way of dropping one. 5 variations · 16 problems - 9 Interval DP: solve every range, short to long
dp[i][j]is the answer for the rangei..j. Try every split pointkinside it and combine the two sides. Fill by range length so the smaller ranges are ready. 3 variations · 6 problems - 10 Tree DP: answers from the children up Root the tree. Each node returns a small tuple of answers for its subtree (for example "with the edge to my parent kept" and "without it"), built from its children's tuples. Process children before parents. 1 variation · 1 problem
- 11 Bitmask DP: a subset as the state When n is small (about 20 or less), store "which items are already used" as the bits of an integer.
dp[mask]is the best answer for that subset, built from a smaller mask with one item or one group removed. 2 variations · 6 problems - 12 Combinatorics: count with a formula Some counting DPs collapse into a formula. Choose where something happens with
C(n, k), multiply the options for the rest, and do it all mod 1e9 + 7 with factorials and modular inverses. 1 variation · 1 problem