Skip to content

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.

21 min read0/7 questions

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):

Calls made by fib(5)
fib(5)fib(1)fib(0)fib(2)fib(1)fib(3)fib(1)fib(0)fib(2)fib(4)fib(1)fib(0)fib(2)fib(1)fib(3)root

One call becomes two, each of those becomes two, and so on. The tree roughly doubles at every level.

1/4

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) from ways(n-1) and ways(n-2)).
Quick check
Plain recursive fib(n) takes about 2ⁿ calls. What is the main reason?
Need a nudge? A hint rules out a wrong answer.

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.

Python
from functools import cache calls = 0 @cache # remembers every result by its argumentsdef climb(n): global calls calls += 1 if n <= 1: return 1 return climb(n - 1) + climb(n - 2) print(climb(40), "in", calls, "calls")
Output
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.

Filling dp for climbing stairs, n = 6
1
0
1
1
2
3
4
5
6

Base cases: dp[0] = 1 (stand still) and dp[1] = 1 (one 1-step).

1/5
Python
def climb(n): dp = [0] * (n + 1) dp[0] = 1 if n >= 1: dp[1] = 1 for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] def climb_small(n): # only the last two values are ever needed prev, cur = 1, 1 for _ in range(n - 1): prev, cur = cur, prev + cur return cur print(climb(6), climb_small(6), climb(45))
Output
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.

Predict the outputPython

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])
Need a nudge? Hints walk you through it.

The recipe

Every DP solution answers five questions. Write them down before any code.

  1. State: what does dp[i] mean, in words? ("the number of ways to reach step i")
  2. Recurrence: how is dp[i] built from smaller states? Usually by thinking about the last choice.
  3. Base cases: the smallest states you know directly.
  4. Order: fill so every dependency is ready (here, left to right).
  5. Answer: which cell holds the result (dp[n], or the max over all cells).
Put it in order5 steps

Put the DP recipe in the order you should work through it.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

VaguePrecise
dp[i] = the robber's answerdp[i] = the most money from houses 0..i, whether or not house i is robbed
dp[i] = longest increasing subsequencedp[i] = length of the longest increasing subsequence that ends at index i
dp[a] = coinsdp[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.

Quick check
You define dp[i] as "the length of the longest increasing subsequence within nums[0..i]". Why is it hard to write a recurrence?
Need a nudge? A hint rules out a wrong answer.

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 houses 0..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 take

Coin change. Fewest coins from coins that add up to amount, or -1 if impossible.

  • State: dp[a] = fewest coins that make amount a.
  • Recurrence: try each coin as the last coin: dp[a] = 1 + min(dp[a - c]) over coins c ≤ a.
  • Base: dp[0] = 0. Everything else starts at infinity (unreachable).
  • Answer: dp[amount], or -1 if it is still infinity.
Python
def coin_change(coins, amount): INF = float("inf") dp = [0] + [INF] * amount for a in range(1, amount + 1): for c in coins: if c <= a and dp[a - c] + 1 < dp[a]: dp[a] = dp[a - c] + 1 return dp[amount] if dp[amount] != INF else -1 print(coin_change([1, 2, 5], 11)) # 5 + 5 + 1print(coin_change([2], 3)) # impossibleprint(coin_change([1, 3, 4], 6)) # 3 + 3, not 4 + 1 + 1
Output
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.

Quick check
For house robber on [2, 7, 9, 3, 1], what is dp[2] (the best total using houses 0 to 2)?
Need a nudge? A hint rules out a wrong answer.

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.

Python
def rob_line(nums): skip, take = 0, 0 for x in nums: skip, take = take, max(take, skip + x) return take def rob_circle(nums): if len(nums) == 1: return nums[0] # both slices below would be empty # The first and last houses are neighbours, so at most one is robbed. return max(rob_line(nums[1:]), # case 1: never rob house 0 rob_line(nums[:-1])) # case 2: never rob the last house def brute(nums): n, best = len(nums), 0 for mask in range(1 << n): picked = [i for i in range(n) if mask >> i & 1] if all((j - i) % n not in (1, n - 1) for i in picked for j in picked if i < j) or n == 1: best = max(best, sum(nums[i] for i in picked)) return best assert rob_circle([2, 3, 2]) == 3assert rob_circle([1, 2, 3, 1]) == 4assert rob_circle([5]) == 5import randomfor _ in range(1000): nums = [random.randint(0, 9) for _ in range(random.randint(1, 8))] assert rob_circle(nums) == brute(nums), numsprint(rob_circle([2, 3, 2]), rob_line([2, 3, 2]))
Output
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).

Quick check
House Robber II on [2, 3, 2] in a circle. What is the answer, and why is the line answer wrong?
Need a nudge? A hint rules out a wrong answer.

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.

Python
import sysfrom functools import cache @cachedef ways(n): if n <= 1: return 1 return ways(n - 1) + ways(n - 2) print("limit:", sys.getrecursionlimit())try: ways(5 * sys.getrecursionlimit())except RecursionError: print("RecursionError: the call chain is n frames deep") # Fix 1: warm the cache from small to large, so no call goes deep.ways.cache_clear()for i in range(0, 5001, 200): ways(i)print(ways(5000) % 1_000_000_007) # Fix 2 (usually better): bottom-up, no recursion at all.def ways_iter(n): a, b = 1, 1 for _ in range(n - 1): a, b = b, a + b return b if n >= 1 else 1 assert ways_iter(5000) == ways(5000)print(ways.cache_info().currsize, "cached entries")ways.cache_clear() # free memory, reset between test cases
Output
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 problemFamilyTypical stateLesson
One sequence, choice at each position1D lineardp[i]This one
Grid paths, or two strings compared2Ddp[i][j] over prefixes2D Dynamic Programming
Items with weights and a capacity or target sumKnapsackdp[capacity]Knapsack and Subset DP
Increasing subsequence, best subarray, buy/sell/cooldownSequence and state machinedp[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"Intervaldp[i][j] over a range, filled by lengthInterval and Palindrome DP
n is at most about 20, "visit all", "assign each"Bitmaskdp[mask] or dp[mask][last]Bitmask DP and DP on Trees
Input is a tree; parent and child interactTree DPa tuple returned per nodeBitmask 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 the pairs0/5 matched

Match each problem to its DP family.

Choose an item, then its match on the other side.

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 + 1 cells.
  • Using a mutable default or global cache that leaks between test cases.
  • Trusting @cache with 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.
ChallengeEasy

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  →  8

Constraints

  • 1 <= n <= 45
def climb_stairs(n: int) -> int: # The last move was a 1-step or a 2-step. Count both cases. pass
ChallengeMedium

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 <= 100
  • 0 <= nums[i] <= 400
def rob(nums: list[int]) -> int: # At each house, decide: skip it, or take it and skip its neighbour. pass
ChallengeMedium

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         →  0

Constraints

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4
def coin_change(coins: list[int], amount: int) -> int: # Work out the fewest coins for every amount from 0 up to the target. pass
Key terms
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.
Interview pattern: Dynamic Programming36 problemsSpot it: Count the ways · min/max cost · "can you reach…" · overlapping choices