Dynamic Programming
Solve each subproblem once, store it, and build bigger answers from smaller ones.
- result
- visited / done
- active this step
- read by this step
Base case
dp[0] = 0 coins. Every other amount starts at 12, which means “not reachable yet”.
VARIABLES
- a
- -
- dp[1..5]
- 12, 12, 12, 12, 12
- dp[11]
- 12
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
DP breaks a problem into overlapping subproblems, defines a state and a transition between states, and stores the results in a table (bottom-up) or a cache (top-down).
Why it matters
Recursion that recomputes the same states is exponential; storing them makes it polynomial.
Think of it like this
Climbing stairs: the ways to reach step n are the ways to reach n − 1 plus the ways to reach n − 2.
Use it when
- Counting ways, or the min or max over choices
- Optimal substructure plus overlapping subproblems
- Sequences and strings - LCS, edit distance
Avoid it when
- Choices never overlap - plain recursion or greedy is enough
- You must list every solution - use backtracking
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| 1-D DP, e.g. climbing stairs | O(n) | O(n), or O(1) with two variables |
| 2-D DP, e.g. LCS or edit distance | O(n × m) | O(n × m) |
| 0/1 knapsack with capacity W | O(n × W) | O(W) with a 1-D array |
Often confused with: greedy - it commits to one choice; DP compares every choice using stored results.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- n up to a few thousand often means O(n²) DP
- If a brute-force recursion repeats the same arguments, memoize it
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- A wrong base case - for coin change dp[0] must be 0
- Filling the table in an order that reads a state before it’s computed
- Returning the “infinity” value instead of -1
Edge cases to test
- amount = 0 - the answer is 0
- No combination works, e.g. coins [2] and amount 3
- A coin larger than the amount
Knowledge check
Quick check to lock in the intuition.
What makes a problem a good fit for DP?
Practice
Apply what you just watched on real interview problems.