Dynamic programming
Dynamic programming remembers the answers to small problems so each is solved only once: plain recursion makes 13529 calls for climb(20), one line of @lru_cache works out just 20 values, and every DP is a state, a transition, a base case and an order.
A staircase has 40 steps, and each move climbs 1 step or 2. How many ways are there to the top? Written as a recursion on "was the last move 1 step or 2", it is three lines that make over 200 million calls, minutes of work for Python; add one line, @lru_cache, above the function and it works out 40 values and is done in a blink. The only difference is whether the same small problem is solved once or a hundred million times. Dynamic programming (DP) remembers the answers to small problems and works them out in order, so each one is solved only once. It is the most common kind of interview problem and the one people dread most, yet the first step is very concrete: run these four versions yourself and count.
Plain recursion: the same problem, many times
To stand on step n, the last move came either from step n − 1, climbing 1, or from step n − 2, climbing 2. The two cases do not overlap, so add them:
- climb(n) = climb(n − 1) + climb(n − 2)
- climb(1) = 1 (only one way: climb 1), climb(2) = 2 (1 + 1, or 2 at once)
It is the same formula as the last lesson's fib, with the same flaw:
1def climb(n):2 global calls3 calls += 14 if n <= 2:5 return n6 return climb(n - 1) + climb(n - 2)
1calls = 02 3def climb(n):4 global calls5 calls += 16 if n <= 2:7 return n8 return climb(n - 1) + climb(n - 2)9 10for n in [5, 10, 15, 20]:11 calls = 012 ways = climb(n)13 print(f"climb({n}) = {ways}, {calls} calls")
climb(5) = 8, 9 calls climb(10) = 89, 109 calls climb(15) = 987, 1219 calls climb(20) = 10946, 13529 calls
Each time n grows by 5, the calls multiply by about 11. Yet there are only n different small problems, climb(1) to climb(n): nearly all of the 13529 calls recompute something already worked out. Small problems that come up again and again are called overlapping subproblems, the first sign that dynamic programming applies.
How many times does the plain recursive climb(6) call climb in all (counting the outermost call)?
1calls = 02 3def climb(n):4 global calls5 calls += 16 if n <= 2:7 return n8 return climb(n - 1) + climb(n - 2)9 10climb(6)11print(calls)
With naive recursion for fib(n), each time n goes up by 1, the number of calls is multiplied by roughly what?
Merge sort also builds the big answer out of smaller problems' answers. Why doesn't it need memoization?
Remember what is done: lru_cache
The most direct fix: keep a dict, store each answer once it is worked out, and look it up first next time. This is memoisation; the recursion looks just the same, plus two lines, "look it up" and "store it":
1calls = 02memo = {}3 4def climb(n):5 global calls6 calls += 17 if n <= 2:8 return n9 if n in memo: # already done: look it up10 return memo[n]11 memo[n] = climb(n - 1) + climb(n - 2)12 return memo[n]13 14for n in [5, 10, 20, 40]:15 calls = 016 memo.clear()17 ways = climb(n)18 print(f"climb({n}) = {ways}, {calls} calls")
climb(5) = 8, 7 calls climb(10) = 89, 17 calls climb(20) = 10946, 37 calls climb(40) = 165580141, 77 calls
climb(40) makes only 77 calls: each n is really worked out the first time and looked up the second. The standard library already does this: put functools.lru_cache above a function and it keeps "arguments → result" in a dict, returning straight away when the same arguments come again. maxsize=None means no limit, remember everything. cache_info() reports how many calls were hits and how many were misses (really worked out):
After climb(10), what are the cache's statistics?
1from functools import lru_cache2 3@lru_cache(maxsize=None)4def climb(n):5 if n <= 2:6 return n7 return climb(n - 1) + climb(n - 2)8 9climb(10)10print(climb.cache_info())
Memoization written another way: only when n is not in memo (not worked out yet) is it really computed and stored; either way the answer comes from memo. Fill in the blank so the program works out climb(40).
1memo = {}2 3def climb(n):4 if n <= 2:5 return n6 if n memo:7 memo[n] = climb(n - 1) + climb(n - 2)8 return memo[n]9 10print(climb(40))
not in: compute only when it isn't in the table, otherwise skip straight to the stored value. With in, a new n isn't in the table, so the computing is skipped and reading memo[n] fails with KeyError; < and > compare a number with a dict, TypeError.Bottom up: fill a table from small to large
Memoisation is "to get the big one, first go and get the small ones": top down. The other direction works too: since the big ones depend only on the small ones, work them out from small to large, one at a time, up to n. In a list dp, dp[i] is climb(i):
The figure's last remark is the key to the next step: dp[i] needs only the two boxes before it, and anything earlier is never used again. So keep just two variables and slide them forward as you go; this is called rolling:
1def climb_table(n):2 if n <= 2:3 return n4 dp = [0] * (n + 1)5 dp[1], dp[2] = 1, 2 # base cases6 for i in range(3, n + 1): # small to large7 dp[i] = dp[i - 1] + dp[i - 2] # transition8 return dp[n]9 10def climb_two(n):11 if n <= 2:12 return n13 a, b = 1, 2 # a = climb(i - 2), b = climb(i - 1)14 for _ in range(3, n + 1):15 a, b = b, a + b16 return b17 18print(climb_table(10), climb_two(10))19print(climb_table(40), climb_two(40))20print([climb_two(n) for n in range(1, 11)])
89 89 165580141 165580141 [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
The four versions side by side:
| Version | How often each small problem is solved | Time | Extra space |
|---|---|---|---|
| Plain recursion | again and again | O(1.618ⁿ) | O(n) call stack |
Memoised (dict or @lru_cache) | once each | O(n) | O(n) cache + O(n) call stack |
| Bottom-up table | once each | O(n) | an O(n) list |
| Two rolling variables | once each | O(n) | O(1) |
Memoisation and the table do the same work in opposite directions. Memoisation is easy to write (copy the recursion, add one decorator) and solves only the small problems actually needed; the table has no recursion, so no depth limit, and can shrink its space as it does here.
A different recurrence: dp[1] = 1, dp[2] = 1, dp[i] = dp[i − 1] + 2 × dp[i − 2]. Filling the table from small to large, what is dp[6]?
Working out fib(n) with two rolling variables, what are the time and the space?
Rolling two variables to work out climb(10): a and b are the last two terms (climb(1) and climb(2) at first). Put the three lines in the loop in order so the program prints 89.
a = bc = a + bb = c
89
The four steps of DP
Whatever the DP problem, think these four steps through before you write:
- State: what
dp[i](ordp[i][j]) means, said in one sentence. Climbing stairs: "the number of ways to reach step i". - Transition: how
dp[i]comes from smaller states. Usually: how many cases are there for "the last move"? From i − 1, or from i − 2. - Base case: the smallest states are given outright, not by the transition: dp[1] = 1, dp[2] = 2.
- Order: when dp[i] is worked out, the boxes it uses must be ready: here, small to large.
The four steps on a 2D problem, the minimum path sum. A grid holds non-negative numbers; go from the top-left corner to the bottom-right, moving only right or down. What is the smallest total of the numbers along the way?
- State:
dp[i][j]= the smallest path sum from the top-left corner to (i, j). - Transition: the last move into (i, j) came either down from (i − 1, j) or right from (i, j − 1); take the smaller:
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]. - Base case: dp[0][0] = grid[0][0]; row 0 can only come from the left, column 0 only from above.
- Order: row by row, each row left to right, so above and left are always ready.
1def min_path_sum(grid):2 rows, cols = len(grid), len(grid[0])3 dp = [[0] * cols for _ in range(rows)] # independent rows, never [[0] * cols] * rows4 for i in range(rows):5 for j in range(cols):6 if i == 0 and j == 0:7 dp[i][j] = grid[0][0]8 elif i == 0:9 dp[i][j] = dp[i][j - 1] + grid[i][j]10 elif j == 0:11 dp[i][j] = dp[i - 1][j] + grid[i][j]12 else:13 dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]14 return dp15 16dp = min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]])17print(dp)18print(dp[-1][-1])19print(min_path_sum([[1, 2, 3], [4, 5, 6]])[-1][-1])
[[1, 4, 5], [2, 7, 6], [6, 8, 7]] 7 12
The 2D table has R × C boxes at O(1) each: O(R × C) time.
In interviews: for a DP problem, say the four steps out loud first, above all the first one, "what dp[i] means"; once that is clear, the transition usually follows. When the code is written, check the base cases on the smallest input (n = 1, a single box). Then say whether the space can shrink: if it depends only on the row above or the last two values, it can roll.
Climbing stairs (1 or 2 steps at a time) with other starting values: dp[0] = 1 (standing on the ground counts as one way), dp[1] = 1, dp[i] = dp[i − 1] + dp[i − 2]. What is dp[4]?
How many paths across a grid
✓On a grid of m rows and n columns, go from the top-left to the bottom-right corner, moving only right or down. Complete unique_paths(m, n): how many different paths are there? Think in the four steps: dp[i][j] is the number of paths to (i, j).
28 3 1 48620
1def unique_paths(m, n):2 dp = [[1] * n for _ in range(m)] # row 0 and column 0 have just 1 path each3 # every other box: the paths from above + the paths from the left4 return dp[m - 1][n - 1]5 6print(unique_paths(3, 7))7print(unique_paths(3, 2))8print(unique_paths(1, 5), unique_paths(10, 10))
House robber
✓A row of houses, nums[i] the money in house i; you cannot rob two neighbours. Complete rob(nums): the most you can take. State: the most from the first i houses; transition: skip house i (the answer for the first i − 1) or rob it (the answer for the first i − 2 + nums[i]), whichever is larger. Roll two variables only.
4 12 5 0
1def rob(nums):2 prev2, prev1 = 0, 0 # the answers for the first i - 2 and the first i - 1 houses3 for x in nums:4 # the new answer = max(skip x, rob x), then slide both variables one place on5 pass6 return prev17 8print(rob([1, 2, 3, 1]))9print(rob([2, 7, 9, 3, 1]))10print(rob([5]), rob([]))
How you write it at work
@lru_cache(maxsize=None) (or @functools.cache since 3.9) is the quickest way to memoise a recursion, but it has two limits:
1from functools import lru_cache2 3MOD = 1_000_000_0074 5@lru_cache(maxsize=None)6def climb(n):7 if n <= 2:8 return n9 return (climb(n - 1) + climb(n - 2)) % MOD10 11print(climb(100))12print(climb.cache_info())13climb.cache_clear()14 15try:16 climb(100000)17except RecursionError:18 print("memoised recursion 100000 deep: RecursionError")19 20def climb_two(n):21 if n <= 2:22 return n23 a, b = 1, 224 for _ in range(3, n + 1):25 a, b = b, (a + b) % MOD26 return b27 28print(climb_two(100000))
782204094 CacheInfo(hits=97, misses=100, maxsize=None, currsize=100) memoised recursion 100000 deep: RecursionError 967618232
- Depth: memoisation is still recursion. The first climb(n) recurses all the way down to climb(2), and with n at 100000 that is a
RecursionError. When n can be large, write the bottom-up loop. - Arguments must be hashable: the cache uses the arguments as dict keys, so a list argument raises
TypeError; use a tuple or an index instead. - The cache holds on to its memory: for a one-off computation,
cache_clear()when done; a bounded one likemaxsize=128throws out the least recently used when full (the LRU of chapter 1). - When results get huge, problems ask for them modulo 1000000007: reduce after every addition, and the numbers stay small.
A function has @lru_cache on it, and it is called with a list as its argument. What happens?
TypeError: unhashable type: 'list'. Pass a tuple instead, or just an index.Summary
Dynamic programming: each small problem solved once
- When small problems repeat (overlapping subproblems), remember their answers
- Memoisation: recursion + @lru_cache, top down; cache_info() counts the hits
- Bottom up: fill a table in order; roll to a few variables when only the last few are read
- Four steps: state (what dp[i] is), transition, base case, order
- Memoisation has a depth limit too: for large n, write a loop
1@lru_cache(maxsize=None)2def climb(n):3 return n if n <= 2 else climb(n - 1) + climb(n - 2)4a, b = 1, 25for _ in range(3, n + 1):6 a, b = b, a + b