Intro to dynamic programming
Break a problem into overlapping subproblems and remember each answer once.
28 min
Dynamic programming (DP) sounds grand and means this: when a problem is built from smaller versions of itself that overlap, solve each small version once and remember the answer.
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)This is correct but slow: fib(30) makes about 2.7 million calls, because fib(28) is recomputed from scratch inside both fib(30) and fib(29). The calls form a tree full of repeated branches. Remember each answer:
memo = {}
def fib(n):
if n < 2:
return n
if n not in memo:
memo[n] = fib(n - 1) + fib(n - 2)
return memo[n]Now each n is solved once: O(n). That is top-down DP (recursion plus a memo). The same idea written as a loop that fills a table from the bottom is bottom-up DP, usually with less overhead.
- 1.State: what small piece of information describes a subproblem? (
dp[i]is the answer using the firstiitems, or for amounti.) - 2.Transition: how does one state come from smaller ones?
- 3.Base case: the smallest states you can answer directly.
- 4.Order: fill states so the ones you need are already done.
- 5.Answer: which state holds it?
Coins [1, 5, 6], amount 10. Greedy (take the biggest coin first) gives 6 + 1 + 1 + 1 + 1 = five coins, but 5 + 5 is two. Greedy fails, so use DP:
- state:
dp[a]= fewest coins to make amounta - transition:
dp[a] = 1 + min(dp[a - c])over every coinc <= a - base:
dp[0] = 0; amounts you cannot make stay at infinity
Pick numbers from a row so that no two chosen numbers are neighbors, maximizing the sum. At each house i you either skip it (best so far is dp[i-1]) or take it (its value plus dp[i-2]):
dp[i] = max(dp[i - 1], dp[i - 2] + a[i])
Since you only need the last two values, you can keep just two variables: O(1) space.
"How many ways", "the minimum or maximum", "is it possible", and a choice at every step with small state. If brute force is exponential but there are only polynomially many distinct subproblems, DP applies.
Move n from 10 to 40. Plain recursion makes about 177 calls for n = 10, and over 300 million for n = 40. With a memo, fib(n) makes only about 2n calls, so n = 40 needs about 80. Overlapping subproblems are why DP exists.
Calls made by plain recursive fib(n)
—
fib(3) and fib(2) appear many times. A memo computes each once.
Write min_coins(coins, amount): the fewest coins from coins (unlimited supply of each) that add up to exactly amount, or -1 if it cannot be done. amount 0 needs 0 coins.
min_coins([1, 5, 6], 10) is 2.
Your code must satisfy
- min_coins([1, 5, 6], 10)→2greedy fails
- min_coins([2], 3)→-1impossible
- min_coins([1, 2], 0)→0zero
- min_coins([7], 21)→3single coin
- min_coins([1, 2, 5], 11)→3mixed
- min_coins([5, 10], 3)→-1no coin fits
def min_coins(coins, amount):
passWrite max_nonadjacent_sum(nums): choose some of the non-negative numbers so that no two chosen numbers are next to each other, and return the largest possible sum. An empty list gives 0. Keep only O(1) extra space.
max_nonadjacent_sum([2, 7, 9, 3, 1]) is 12 (2 + 9 + 1).
Your code must satisfy
- max_nonadjacent_sum([2, 7, 9, 3, 1])→12example
- max_nonadjacent_sum([])→0empty
- max_nonadjacent_sum([5])→5single
- max_nonadjacent_sum([3, 8])→8two
- max_nonadjacent_sum([5, 1, 1, 5])→10alternate
- max_nonadjacent_sum([4, 4, 4, 4, 4])→12all equal
def max_nonadjacent_sum(nums):
pass“Dynamic programming is a special algorithm you have to memorize.”
Textbooks list DP problems as a catalogue of named tricks.
What is actually true
DP is one idea: define small subproblems, relate each to smaller ones, and never solve the same one twice. Once you can write the state and the transition in a sentence, the code is short.
How to catch yourself
Start with plain recursion for the brute force, spot the repeated calls, then add a memo.
- DP solves each overlapping subproblem once and remembers it: exponential recursion becomes polynomial.
- Recipe: define the state, the transition, the base case, the order and where the answer lives.
- Top-down is recursion plus a memo; bottom-up fills a table in order. Both give the same answer.
- Greedy can fail where DP works: coins
[1, 5, 6]for 10.
DP checks.
What is fib(10) with fib(0) = 0 and fib(1) = 1?
What makes a problem suit DP?
- AA sorted input
- BOverlapping subproblems that repeat
- CStrings only
- DA graph
Fewest coins from [1, 3, 4] to make 6?
What is the base case of the coin DP?
- A`dp[amount] = 0`
- B`dp[0] = 0`
- C`dp[1] = 1`
- DThere is none
Which is the transition for no-two-neighbors?
- A`dp[i] = dp[i-1] + a[i]`
- B`dp[i] = max(dp[i-1], dp[i-2] + a[i])`
- C`dp[i] = min(dp[i-1], a[i])`
- D`dp[i] = a[i]`
Your interview checklist
Practice out loud. Explaining the choice of structure is half the score.
Which of the nine patterns felt hardest to recognize? Write one sentence that would help you spot it in a new problem.
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Coding Interview Prep: Data Structures and Algorithms is planned around your week. Free.