Dynamic programming: core concepts
medium 18 minDynamic programming solves a problem by breaking it into smaller subproblems, solving each distinct subproblem once and storing the answer.
See it run
Watch repeated subproblems appear, collapse into memo hits, then turn into a table filled in order and finally two rolling variables.
Operations
Overlapping subproblems: fib(5)
Grow the naive call tree for fib(5) and count how often each question is asked. Only 6 distinct questions exist, yet the tree makes 15 calls: that waste is what dynamic programming removes.
Step 1 of 6
One question: fib(5)
calls: 1
We want fib(5). It is not a base case, so the function asks two smaller questions: fib(4) and fib(3). Nothing is remembered between calls.
Step 1: One question: fib(5)
def fib(n): if n <= 1: return n # base cases: fib(0) = 0, fib(1) = 1 return fib(n - 1) + fib(n - 2) # two smaller questions, often repeatsprint(fib(5)) # 5, after 15 calls- Time
- Θ(φⁿ), about O(2ⁿ)
- Space
- O(n) call stack
- fib(5)
- 15 calls, 6 distinct
- fib(10)
- 177 calls, 11 distinct
Before reaching for DP, draw two or three levels of the brute-force call tree. If the same arguments show up in different branches, you have overlapping subproblems.
In the real world
The same dynamic programming: core concepts doing real jobs. Pick one and step through it.
If someone asks you what 2 + 2 is, you say 4. Asked again ten seconds later, you do not recalculate: you remember. DP is a notebook of answers you write once and look up forever.
Step 1 of 4
First time: work it out
| 2 + 2 | fib(10) | paths 3×4 | |
|---|---|---|---|
| answer | 4 | · | · |
| asked | 1 | 0 | 0 |
| worked out | 1 | 0 | 0 |
written down: 2 + 2 = 4
Someone asks 2 + 2. You have not seen it before, so you work it out, get 4, and write it in the notebook.
Step 1: First time: work it out
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Filling the table in the wrong order
criticalBottom-up only works if every cell's inputs are filled before the cell itself. Walking columns right to left reads
dp[r][c - 1]while it is still 0, so the answers come out too small with no error to warn you.Wrongfor r in range(1, rows): for c in range(cols - 1, 0, -1): # right to left dp[r][c] = dp[r - 1][c] + dp[r][c - 1] # left cell not filled yetRightfor r in range(1, rows): for c in range(1, cols): # left to right: inputs ready dp[r][c] = dp[r - 1][c] + dp[r][c - 1]A state that leaves out a variable
criticalThe memo key must include everything the answer depends on. In 0/1 knapsack the best value depends on the item index and the remaining capacity; keying the memo on the index alone returns an answer computed for a different capacity.
Wrongdef best(i, cap): if i in memo: # key ignores cap return memo[i] ... memo[i] = resultRightdef best(i, cap): if (i, cap) in memo: # the full state return memo[(i, cap)] ... memo[(i, cap)] = resultA table one cell too short
criticalIf the answer is
dp[n], the table needs n + 1 cells, indexes 0 to n.[0] * nstops atn - 1, and the last line raises IndexError.Wrongdp = [0] * n...return dp[n] # IndexErrorRightdp = [0] * (n + 1) # indexes 0..n...return dp[n]Sliding the rolling variables in the wrong order
majorUpdating
prev2first destroys the oldprev1value that the new sum needs. Compute the new value first, or use tuple assignment so the right side is evaluated before anything is overwritten.Wrongprev2 = prev1prev1 = prev1 + prev2 # adds prev1 to itselfRightprev2, prev1 = prev1, prev1 + prev2 # right side evaluated firstA mutable default argument as the memo
majormemo={}in the signature is created once, when the function is defined, and shared by every call ever made. Results from one input leak into the next, which is wrong as soon as the answer depends on more than the key, such as a different cost list.Wrongdef solve(i, cost, memo={}): # one dict shared forever ...Rightdef solve(i, cost, memo=None): if memo is None: memo = {} ...Deep memoised recursion hitting the recursion limit
minorMemoisation fixes the time, not the depth.
fib(5000)with@cachestill needs about 5,000 nested frames, past Python's default limit of about 1,000. Use the bottom-up loop for large n.Wrong@cachedef fib(n): return n if n <= 1 else fib(n - 1) + fib(n - 2)fib(5000) # RecursionErrorRightdef fib(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b return afib(5000) # fine
Interview tips
How to explain it
- DP needs overlapping subproblems (the same questions repeat) and optimal substructure (the answer is built from answers to smaller questions).
- Name the state, the transition, the base cases and the order before writing code.
- Time is the number of states times the work per state; space is the states you keep.
Spot it in problems
- The question asks for a count of ways, a minimum or maximum, or whether something is possible.
- Each choice changes what is possible later, so a greedy pick can fail.
- Your brute-force recursion calls itself with the same arguments in different branches.
Memory tricks
- MOST: Memoise to avoid recomputation, Optimal substructure, Subproblems overlap, Table stores results.
- The notebook: work an answer out once, write it down, look it up after.
- fib(10): 177 calls naive, 19 with a memo.
Interview flow
- Say the brute-force recursion out loud first, then point at the repeated arguments.
- Add a memo for a working O(states) solution, then convert to a table if asked.
- Finish with the space optimisation and the final time and space.