Lesson 25 of 40Advanced patterns
Dynamic Programming
Turn slow recursion into fast code by caching repeated subproblems, define the state in words, and recognise which DP family a problem belongs to.
Dynamic programming (DP) has a scary reputation, but the idea is small: if you keep solving the same subproblem, solve it once and remember the answer. That one change can turn an algorithm that would take years into one that finishes in microseconds. In Backtracking you tried every choice; DP is what you reach for when those choices keep landing on the same subproblems.
DP is behind spell-check suggestions (edit distance), diff and git (longest common subsequence), route planning, and resource budgeting. In interviews it is the topic candidates fear most, so having a reliable recipe is a real advantage.
The problem with plain recursion
Climbing stairs: you can climb 1 or 2 steps at a time. How many different ways are there to reach step n?
Think about the last move. To stand on step n you came from step n − 1 (with a 1-step) or step n − 2 (with a 2-step). So:
ways(n) = ways(n - 1) + ways(n - 2), with ways(0) = 1 and ways(1) = 1.
That is the Fibonacci recurrence. Written as plain recursion, it is correct and painfully slow. Watch the calls for n = 5 (using the name fib, since it is the same function):
One call becomes two, each of those becomes two, and so on. The tree roughly doubles at every level.
Two properties make a problem a DP problem:
- Overlapping subproblems: the same smaller question comes up again and again (like
fib(2)above). - Optimal substructure: the answer to the big question can be built from answers to smaller ones (like
ways(n)fromways(n-1)andways(n-2)).
fib(n) takes about 2ⁿ calls. What is the main reason?Step 1: memoization (top-down)
Memoization keeps the recursive code and adds a cache. Before computing fib(k), check if it is already known. After computing it, store it. Each distinct subproblem is now solved once.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Without the cache, climb(40) makes about 330 million calls. With it, about 40. Time is O(n) and space is O(n) for the cache plus the recursion stack. functools.cache (Python 3.9+) is the same as lru_cache(maxsize=None).
Step 2: tabulation (bottom-up)
Tabulation flips the direction. Instead of starting at n and recursing down, start at the base cases and fill a table upward, so every value you need is already there when you get to it. No recursion, so no stack limit.
Base cases: dp[0] = 1 (stand still) and dp[1] = 1 (one 1-step).
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Since each cell only reads the previous two, you can keep just two variables: O(n) time, O(1) space. Memoization and tabulation have the same big-O; tabulation is usually a little faster and avoids recursion limits, while memoization is easier to write from a recursive idea and skips subproblems you never need.
Same staircase, but you can climb 1, 2 or 3 steps at a time. What is printed?
dp = [1, 1, 2] for i in range(3, 6): dp.append(dp[i - 1] + dp[i - 2] + dp[i - 3]) print(dp[5])
The recipe
Every DP solution answers five questions. Write them down before any code.
- State: what does
dp[i]mean, in words? ("the number of ways to reach step i") - Recurrence: how is
dp[i]built from smaller states? Usually by thinking about the last choice. - Base cases: the smallest states you know directly.
- Order: fill so every dependency is ready (here, left to right).
- Answer: which cell holds the result (
dp[n], or the max over all cells).
Put the DP recipe in the order you should work through it.
- Tap the steps below in the right order.
Say the state in words before you write code
Most wrong DP solutions are wrong in the first line, the state, not in the loop. So write the state as a full English sentence, and make it precise about three things: which part of the input it covers, what extra condition it carries, and what quantity it holds.
| Vague | Precise |
|---|---|
dp[i] = the robber's answer | dp[i] = the most money from houses 0..i, whether or not house i is robbed |
dp[i] = longest increasing subsequence | dp[i] = length of the longest increasing subsequence that ends at index i |
dp[a] = coins | dp[a] = the fewest coins whose values add up to exactly a |
The middle row shows why the wording matters. "LIS of nums[0..i]" sounds equivalent, but it gives you no recurrence: to extend a subsequence with nums[i] you need to know what its last value was. "Ends at i" carries exactly that, and the final answer becomes max(dp) instead of dp[n-1]. Whenever the answer is "the max over all cells" rather than "the last cell", it is usually because the state was pinned to an ending position.
Then run one test on your sentence: does the state carry everything the future needs? For each later choice, ask "can I decide it knowing only this state?" If not, the state is missing a dimension. Stock trading with a cooldown fails the test with dp[i] = best profit by day i, because whether you may buy on day i + 1 depends on whether you hold a share and whether you sold yesterday. Adding that as a second index, dp[i][holding], fixes it. That is the state-machine family in LIS, Subarray and State-Machine DP. The opposite mistake is a state with too much in it, such as the whole path so far, which makes the number of states exponential. If two different histories lead to the same future, they belong in the same state.
The decision at step i
Once the state is written, the recurrence comes from one question: at step i, what are my options, and what does each one leave me with? List the options, express each as "this step's contribution plus a smaller state", and combine them with the right operation: max or min for optimisation, + for counting, or for "is it possible".
- Take or skip item i: house robber, 0/1 knapsack. Two options per step.
- Which item goes last: coin change ("the last coin was c"), climbing stairs ("the last move was 1 or 2"). One option per choice.
- Extend or start fresh: Kadane and LIS ("which earlier element do I extend?").
- Where to split: interval DP ("the last balloon burst between i and j was k").
For house robber, the decision at house i is rob or skip. Skip leaves the best from 0..i-1. Rob gives nums[i] and leaves the best from 0..i-2, because the neighbour is off limits. So dp[i] = max(dp[i-1], nums[i] + dp[i-2]). Say the decision out loud in the interview before writing the formula; it shows the interviewer the recurrence is derived, not memorised.
dp[i] as "the length of the longest increasing subsequence within nums[0..i]". Why is it hard to write a recurrence?Two more 1D examples
House robber. Houses in a row hold nums[i] money. You cannot rob two neighbours. What is the most you can take?
- State:
dp[i]= the best total using houses0..i. - Recurrence: for house i, either skip it (
dp[i-1]) or rob it (nums[i] + dp[i-2]). Take the larger. - Answer:
dp[n-1]. As with stairs, two variables are enough.
def rob(nums):
skip, take = 0, 0 # best up to i-2, best up to i-1
for x in nums:
skip, take = take, max(take, skip + x)
return takeCoin change. Fewest coins from coins that add up to amount, or -1 if impossible.
- State:
dp[a]= fewest coins that make amounta. - Recurrence: try each coin as the last coin:
dp[a] = 1 + min(dp[a - c])over coinsc ≤ a. - Base:
dp[0] = 0. Everything else starts at infinity (unreachable). - Answer:
dp[amount], or -1 if it is still infinity.
Press Run (⌘ Enter) to see what happens.That runs in O(amount × number of coins). The last example matters: always taking the biggest coin gives 4 + 1 + 1 (three coins), but the best is 3 + 3. Greedy fails here; DP considers every last coin.
[2, 7, 9, 3, 1], what is dp[2] (the best total using houses 0 to 2)?House Robber II: break the circle into two lines
Same street, but the houses stand in a circle, so the first and last houses are neighbours. Your line-based DP has no way to remember, at the last house, whether the first one was robbed.
You could add that to the state, but a simpler trick works: split by cases. The first and last houses cannot both be robbed, so every valid plan either never robs house 0 or never robs the last house (or both). Solve the plain line problem twice, once on nums[1:] and once on nums[:-1], and take the better result. Each case is now a line, so the original two-variable DP applies unchanged.
Press Run (⌘ Enter) to see what happens.Still O(n) time and O(1) extra space (the slices copy the list; pass index ranges instead if memory matters). The single-house case needs its own line, because both slices would be empty and return 0. The brute force tries every subset on small inputs and checks the circular neighbour rule, which is a good way to confirm a case split you came up with under pressure.
"Break a cycle by fixing what happens at one point, then solve the line" is a general move. It returns in circular arrays (Maximum Sum Circular Subarray: either the best subarray does not wrap, or it is the total minus the worst non-wrapping subarray) and in House Robber III, where the street becomes a tree (Bitmask DP and DP on Trees).
[2, 3, 2] in a circle. What is the answer, and why is the line answer wrong?Memoisation in Python: functools.cache and its traps
@cache is the fastest way from a correct recursion to an efficient one, and in an interview it is perfectly acceptable. It has three traps worth knowing before they bite.
1. Recursion depth. Memoisation removes repeated work, but not depth. climb(n) still calls climb(n - 1) before anything is cached, so the call chain is n frames deep. Python's default recursion limit is 1000 (see sys.getrecursionlimit()), and neither CPython nor JavaScript engines optimise tail calls, so a memoised solution that is correct for n = 500 raises RecursionError at n = 5000.
Press Run (⌘ Enter) to see what happens.You can raise the limit with sys.setrecursionlimit, but that only moves the problem: each Python frame also uses the underlying C stack, and a very high limit can crash the interpreter outright instead of raising a clean error. When the constraints allow n in the tens of thousands, write it bottom-up. Recursion to Iteration walks through that conversion step by step.
2. A cache that outlives the test case. A @cache on a module-level function keeps its entries between calls. If the function reads anything that is not an argument, such as a nums list from an outer scope that changes between test cases, the second test reuses answers computed for the first. Define the memoised helper inside the solving function, so each call gets a fresh cache, or call cache_clear().
3. Arguments must be hashable. The cache is a dict keyed by the arguments, so passing a list raises TypeError. Pass indexes into the list instead of slices (solve(i) rather than solve(nums[i:])), which is also faster, because slicing copies. Use a tuple or a bitmask when the state really is a collection.
lru_cache(maxsize=N) bounds memory by evicting old entries, which is useful in long-running services but usually wrong for DP, where evicted subproblems get recomputed. In TypeScript, the equivalent is a Map keyed by a number or a string like `${i},${j}`, created inside the solving function for the same reason as trap 2.
Which DP family is this?
DP problems come in a handful of families, and recognising the family gives you the state shape before you start. This lesson covered the 1D "one index" family. The rest each have their own lesson.
| Clue in the problem | Family | Typical state | Lesson |
|---|---|---|---|
| One sequence, choice at each position | 1D linear | dp[i] | This one |
| Grid paths, or two strings compared | 2D | dp[i][j] over prefixes | 2D Dynamic Programming |
| Items with weights and a capacity or target sum | Knapsack | dp[capacity] | Knapsack and Subset DP |
| Increasing subsequence, best subarray, buy/sell/cooldown | Sequence and state machine | dp[i] ends at i, or dp[i][state] | LIS, Subarray and State-Machine DP |
| Answer for a range built from smaller ranges; palindromes; "the last one removed" | Interval | dp[i][j] over a range, filled by length | Interval and Palindrome DP |
| n is at most about 20, "visit all", "assign each" | Bitmask | dp[mask] or dp[mask][last] | Bitmask DP and DP on Trees |
| Input is a tree; parent and child interact | Tree DP | a tuple returned per node | Bitmask DP and DP on Trees |
Two quick tells cut through most of it. Look at the constraints: n up to about 20 suggests bitmasks, n up to a few thousand allows O(n²) (2D or interval), and n up to 10⁵ or more needs O(n) or O(n log n) (1D, or a sequence DP with binary search). Then look at what the answer depends on: a prefix, a pair of prefixes, a range, a capacity, or a set.
Match each problem to its DP family.
Common mistakes:
- Starting to code before writing what
dp[i]means. - Wrong base cases (is
dp[0]0 or 1? Ask what the empty case means: one way to climb zero stairs; zero coins to make zero). - Off-by-one table sizes: you usually need
n + 1cells. - Using a mutable default or global cache that leaks between test cases.
- Trusting
@cachewith n in the thousands: it removes repeated work, not recursion depth. - Forgetting the one-house case in House Robber II, where both slices are empty.
- Reaching for greedy on problems like coin change, where the locally best choice is not safe.
Climbing Stairs
A staircase has n steps. Each move, you climb either 1 or 2 steps. Return how many different sequences of moves get you exactly to the top.
n = 2 → 2 (1+1, 2)
n = 3 → 3 (1+1+1, 1+2, 2+1)
n = 5 → 8Constraints
1 <= n <= 45
House Robber
Houses along a street hold nums[i] coins each. You may collect from any houses you like, but never from two neighbours, because adjacent alarms are linked. Return the most coins you can collect.
nums = [1, 2, 3, 1] → 4 (houses 0 and 2)
nums = [2, 7, 9, 3, 1] → 12 (houses 0, 2 and 4)
nums = [2, 1, 1, 2] → 4 (houses 0 and 3)An empty street gives 0.
Constraints
0 <= nums.length <= 1000 <= nums[i] <= 400
Coin Change
You have unlimited coins of each value in coins. Return the fewest coins that add up to exactly amount, or -1 if no combination works.
coins = [1, 2, 5], amount = 11 → 3 (5 + 5 + 1)
coins = [2], amount = 3 → -1
coins = [1], amount = 0 → 0Constraints
1 <= coins.length <= 121 <= coins[i] <= 2^31 - 10 <= amount <= 10^4
- overlapping subproblems
- The same smaller question is asked many times, so caching its answer saves work.
- optimal substructure
- The best answer to the whole problem is built from best answers to smaller problems.
- memoization
- Top-down DP: recursive code plus a cache keyed by the arguments.
- tabulation
- Bottom-up DP: fill a table from the base cases upward in dependency order.
- state
- What one cell of the DP table means, in words. Define it before writing any code.
- recurrence
- The formula for a state in terms of smaller states, usually found by considering the last choice.
- decision at step i
- The options available at one step, each written as its contribution plus a smaller state, then combined with max, min, + or or.
- recursion limit
- Python's cap on call depth, 1000 by default. Memoised recursion still hits it on long chains; bottom-up avoids it.