Dynamic Programming: Stop Solving the Same Problem Twice
You're climbing a staircase with 10 steps, and you can take either 1 or 2 steps at a time. How many different ways can you reach the top?
If you try to list them all, you'll get lost quickly. But notice something: to land on step 10, your last move came from either step 9 or step 8. So the number of ways to reach step 10 is just the ways to reach step 9 plus the ways to reach step 8. And the same logic applies to those, all the way down.
That way of thinking, where the answer to a big problem is assembled from answers to smaller ones, is dynamic programming. The name sounds grander than it is. (It was picked in the 1950s partly because it sounded impressive. The "programming" part means planning, not writing code.)
The two properties you need
Dynamic programming (DP) works when a problem has both of these:
Overlapping subproblems. The same smaller questions get asked again and again. In the staircase, "how many ways to reach step 5?" comes up from many directions.
Optimal substructure. The best answer to the whole problem can be built from the best answers to its pieces. If the cheapest route from A to C passes through B, then the A-to-B part of it must itself be the cheapest way to get from A to B.
If the subproblems don't overlap, plain divide-and-conquer is enough. If the best solution can't be built from best sub-solutions, DP gives the wrong answer.
Seeing the waste
Here's the naive recursive solution for Fibonacci numbers, which is the staircase problem in disguise:
python
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
It's elegant and terribly slow. fib(5) calls fib(3) twice, fib(2) three times, and so on. The number of calls roughly doubles every time n grows by one, so fib(50) would take longer than you're willing to wait. Almost all of that work is repetition.
DP's whole trick is: compute each subproblem once, write the answer down, and look it up next time.
Two ways to do it
Top-down (memoization)
Keep the recursive structure, but add a cache.
python
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Now fib(50) returns instantly. Each value from 0 to 50 is computed exactly once. The running time drops from exponential to linear.
Bottom-up (tabulation)
Start from the smallest cases and fill a table upwards.
python
def fib(n):
if n < 2:
return n
prev, curr = 0, 1
for _ in range(2, n + 1):
prev, curr = curr, prev + curr
return curr
This version has no recursion, no risk of hitting a recursion limit, and, because each value only needs the previous two, it uses just two variables instead of a whole table.
Which should you choose? Top-down is usually easier to write because it mirrors how you think about the problem. Bottom-up is usually a bit faster and easier to optimize for memory.
A recipe for solving DP problems
When you meet a new problem, walk through these steps:
- Define the state. What small set of numbers pins down a subproblem? For the staircase, it's just the step number.
- Write the recurrence. How does a state's answer depend on smaller states? (ways[i] = ways[i-1] + ways[i-2])
- Set the base cases. What are the answers so trivial you can state them directly?
- Decide the order. Make sure you compute dependencies before the things that need them.
- Find the answer. Which state holds what the question asked for?
- Optimize space if the recurrence only looks back a few steps. In my experience, step 1 is where most of the difficulty lives. Once you've picked the right state, the rest tends to fall into place.
A richer example: 0/1 knapsack
You have a backpack that holds up to a certain weight, and a set of items, each with a weight and a value. Each item can be taken once or left. Which items give you the highest total value without overloading the bag?
Trying every subset takes exponential time. With DP:
- State: dp[i][w] is the best value you can get using the first i items with a weight limit of w.
- Recurrence: for item i, either skip it (dp[i-1][w]) or, if it fits, take it (value[i] + dp[i-1][w - weight[i]]). Keep the larger.
- Base case: with no items, the value is 0.
python
def knapsack(weights, values, capacity):
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(capacity + 1):
dp[i][w] = dp[i - 1][w]
if weights[i - 1] <= w:
take = values[i - 1] + dp[i - 1][w - weights[i - 1]]
dp[i][w] = max(dp[i][w], take)
return dp[n][capacity]
print(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9
The running time is O(n * capacity), which is vastly better than trying every combination.
Another classic: edit distance
How many single-character insertions, deletions or substitutions turn "kitten" into "sitting"? This is what spell checkers and diff tools compute. The state is dp[i][j], the cheapest way to convert the first i characters of one word into the first j characters of the other. If the characters match, no cost is added. Otherwise you take the cheapest of insert, delete or replace, plus one. The answer here is 3.
Where else DP appears
- Shortest paths in graphs (Bellman-Ford, Floyd-Warshall)
- Longest common subsequence and longest increasing subsequence
- Coin change and making change with the fewest coins
- Matrix chain multiplication
- Text justification and line breaking
- Sequence alignment in bioinformatics
- Resource allocation and scheduling
Common mistakes
- Choosing a state that's too small, so it doesn't capture everything the future depends on. If your recurrence needs information your state doesn't hold, add it to the state.
- Choosing a state that's too big, so the table becomes impractical.
- Wrong iteration order in bottom-up solutions, reading cells you haven't filled yet.
- Forgetting base cases or using the wrong ones.
- Using DP where greedy would do, or the reverse. Greedy methods pick the locally best option and never look back, and they only work when that's provably safe.
How to practise
Start with the staircase, Fibonacci, and coin change. Move on to knapsack, longest common subsequence and edit distance. Then try grid problems like counting paths with obstacles. For each, say the state and the recurrence out loud before writing any code. After a dozen or so, the pattern starts to feel almost automatic.
Takeaways
- DP solves big problems by combining answers to smaller, repeating ones.
- It needs overlapping subproblems and optimal substructure.
- Memoization (top-down) and tabulation (bottom-up) are two routes to the same result.
- The hard part is choosing the state; the recurrence follows from it.
- It can turn exponential-time brute force into polynomial time.
