Dynamic Programming
Dynamic programming solves a problem by splitting it into smaller subproblems that repeat, solving each one once, and storing the answers in a table. It applies when subproblems overlap and the best answer is built from best answers to smaller ones.
The Two Conditions
Dynamic programming (DP) solves a problem by breaking it into subproblems, solving each one once, and storing the result for reuse. It only helps when two properties hold, and checking them is how you decide whether DP fits.
Overlapping subproblems means the same subproblem comes up again and again. Plain recursive Fibonacci makes 2,692,537 calls to compute fib(30), yet there are only 31 different values fib(0) to fib(30). Storing each value the first time cuts the work to 31 computations.
This is what separates DP from divide and conquer. Merge sort also splits and recurses, but its halves never overlap, so there is nothing to store. No overlap, no DP.
Optimal substructure means the best answer is built from best answers to smaller problems. The shortest path from A to C through B contains a shortest path from A to B; if a shorter A-to-B route existed, swapping it in would shorten the whole path.
This property can fail. The longest simple path in a graph does not have it: joining two longest sub-paths can visit a vertex twice, so the result is not a simple path. That problem is NP-hard, and no DP over the obvious states solves it.
- Overlapping subproblems: the same subproblem recurs
- Optimal substructure: best whole from best parts
- No overlap means divide and conquer, not DP
Defining the State
Almost all the difficulty in a DP problem lies here, and almost none in the coding. The state is the set of parameters that uniquely identify a subproblem — and choosing it well is what makes the recurrence appear almost automatically.
A useful test: if you paused halfway, what would you need to know to finish correctly? That, and nothing more, is the state. In coin change it is just the amount still to make; which coins were used to get there does not matter. In the 0/1 knapsack it is the item being considered and the capacity left.
Get this wrong in either direction and the solution fails. Too little and different situations collapse into one cache entry, returning answers from the wrong context. Too much and the state space explodes, making a correct solution too slow to run.
With the state fixed, write the recurrence: how one state's answer is built from smaller states. It usually tries every choice at that state and keeps the best. For coin change the choice is the last coin: dp[a] = 1 + min(dp[a - c]) over every coin c ≤ a. For knapsack it is skip the item or take it.
Then the base cases: states with nothing smaller beneath them, such as amount 0, an empty array or zero capacity. Also choose the starting value for every other state carefully. In coin change, unreachable amounts must start at infinity; starting them at 0 claims they cost nothing and corrupts every cell that reads them.
The cost follows from the state: number of states × work per state. Coin change has amount + 1 states and tries every coin at each, so O(amount × coins). Knapsack with n items and capacity W is O(n·W). That is pseudo-polynomial: W is a number, not an input length, so a capacity of a billion makes the table impractical however few items there are.
- State = what you need to know to finish from here
- Too few parameters merge different situations; too many blow up the table
- Base cases and starting values matter as much as the recurrence
Memoization and Tabulation
There are two ways to implement the same recurrence. They compute the same values in a different order.
Memoization is top-down: write the plain recursion, then add a cache that returns a stored answer if the state was solved before. It is the easier one to derive, and it only computes states the input actually reaches. Its costs are the call stack (Python stops at 1,000 frames by default) and function-call overhead.
Tabulation is bottom-up: allocate the table, fill in the base cases, then loop over states in an order where every state a cell reads is already filled. There is no recursion and no stack limit, and the plain loops are usually faster. The code below tabulates Fibonacci: dp[i] = dp[i - 1] + dp[i - 2] for i from 2 up to n.
The catch is that you choose the fill order, and a wrong order reads a cell before it is written. Nothing crashes; the answer is simply built on starting values. Tabulation also fills every state, including ones the input never needs.
Tabulation makes one saving easy. When each row reads only the previous row, keep just that row (a rolling array). Knapsack drops from O(n·W) to O(W) space this way, and Fibonacci from O(n) to two variables. In the one-row 0/1 knapsack, capacity must be looped downward, or an item gets used twice; looping upward is exactly the unbounded knapsack.
- Memoization: recursion + cache, computes only reachable states
- Tabulation: loops in dependency order, no stack risk
- Rolling arrays keep only the rows still being read
Terms, operations, and practical uses
Core vocabulary
- StateA set of parameters that uniquely identify a specific subproblem (e.g.,
indexandcurrent_capacity). - TransitionThe mathematical relationship between a state and its smaller sub-states (the recurrence relation).
- MemoizationCaching the results of expensive function calls to return the cached result when the same inputs occur again (Top-Down).
Key concepts
- Overlapping SubproblemsWhen a problem is broken down into subproblems which are reused several times.
- Optimal SubstructureWhen an optimal solution can be constructed efficiently from optimal solutions of its subproblems.
- TabulationSolving a DP problem by filling up a table (array) iteratively from the smallest subproblem up to the final answer (Bottom-Up).
Common patterns
- 1D DPProblems where the state can be represented by a single integer, like climbing stairs.
- 2D DPProblems where the state requires two integers, such as navigating a grid or comparing two strings.
- KnapsackA classic pattern involving choosing items with weights and values to maximize total value within a capacity.
Code in Python, C++ and Java
def fib(n):
if n <= 1:
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]
print(fib(5))#include <iostream>
#include <vector>
using namespace std;
int fib(int n) {
if (n <= 1) return n;
vector<int> dp(n + 1, 0);
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
int main() {
cout << fib(5) << '\n';
}public class Main {
static int fib(int n) {
if (n <= 1) return n;
int[] dp = new int[n + 1];
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
public static void main(String[] args) {
System.out.println(fib(5));
}
}Step through it
Running on coins = [1, 3, 4], amount = 6
Worked Example: Coin Change
Make 6 from coins 1, 3 and 4 with as few coins as possible. Greedy takes the largest coin first, 4 + 1 + 1, which is three coins. The best answer is 3 + 3, two coins.
Let dp[a] be the fewest coins that make a, with dp[0] = 0 and every other cell starting at infinity. Fill a from 1 to 6 with dp[a] = 1 + min(dp[a - c]). The table comes out [0, 1, 2, 1, 1, 2, 2], so the answer is dp[6] = 2. Recording which coin won each cell lets you walk back from 6: coin 3 to amount 3, coin 3 again to 0.
The tracer below fills every cell and shows the reads behind it, then the classic mistakes: filling in the wrong order, and starting unreachable cells at 0. The full problem is Coin Change; counting the ways instead of the fewest coins is Coin Change II, where the min becomes a sum.
- 7 states × 3 coins = 21 table reads
- If an amount cannot be made, its cell stays at infinity and the answer is -1
Recognising a DP Problem
- Write the brute-force recursion that tries every choice
- Find which parameters change between calls: that is the state
- Add a cache (memoization) and check the answers
- If needed, turn it into a table filled in dependency order
- If each row reads only the last one, keep just that row
The signals are consistent. The problem asks for a maximum, a minimum or a number of ways, not one particular arrangement. It involves a sequence of choices, each changing what is left. A greedy choice fails on some input you can construct. And the brute-force recursion is exponential with visibly repeated calls.
Counting problems are a strong hint: 'how many ways' sums over subproblems and rarely has a greedy solution. The comparison with greedy matters because the two look alike. Greedy commits to the best-looking option and never reconsiders; it is right only when a proof says that option is safe. Fractional knapsack is greedy (best value per weight first), while 0/1 knapsack is DP, because items cannot be split. The greedy algorithms lesson covers when greedy is safe.
Common families: knapsack (0/1 Knapsack) for choosing items under a budget, Longest Common Subsequence and Edit Distance for comparing two sequences, and Longest Increasing Subsequence, whose O(n log n) solution uses binary search rather than the obvious O(n²) table. The smallest DP of all is Kadane's algorithm, where the table shrinks to one running value. Easy first problems: Climbing Stairs and House Robber.
- Max, min or count of ways over a sequence of choices
- If greedy fails on a small case you can build, suspect DP