5. Graphs & Dynamic Programming
Dynamic Programming: Memoization vs Bottom-Up Tabulation
Stop fearing Dynamic Programming: learn how overlapping subproblems turn exponential recursion into O(n) via @functools.lru_cache (top-down) and DP tables (bottom-up).
- Spot overlapping subproblems and optimal substructure in recursion trees
- Write Top-Down DP effortlessly in Python using @functools.lru_cache
- Convert Top-Down transitions into iterative Bottom-Up DP arrays with O(1) space optimization
Dynamic Programming (DP) has an intimidating reputation, yet it comes down to one practical idea: Recursion + Caching repeated work (Top-Down), or filling a small table from base cases upward (Bottom-Up).
Why It Matters: Eliminating Exponential Re-Computation
Consider House Robber (nums = [2, 7, 9, 3, 1]): you want the maximum loot without robbing two adjacent houses.
- Naive recursion: At index
i, try skipping (dp(i + 1)) or robbing (nums[i] + dp(i + 2)). Without caching,dp(3)anddp(4)are recomputed exponentially many times →O(2ⁿ)(completely stalls atn = 45!). - DP (Memoization or Tabulation): Each state
ifrom0ton - 1is solved once →O(n)time (andO(1)space when compressed!).
When Does DP Apply? (2 Tell-Tale Clues)
- Optimization or Counting: The prompt asks for "minimum cost", "maximum profit", "longest sequence", or "number of ways"—and greedy fails!
- Overlapping Subproblems + Optimal Substructure: The recursion tree visits identical
(state)arguments over and over, and the best answer for a state builds purely from smaller sub-states.
Approach A: Top-Down Memoization (@lru_cache)
In interviews, Top-Down is the fastest way to get a clean, working solution on the board. Define the state dp(i), write the base case, write the recurrence, and add @functools.lru_cache(maxsize=None):
from functools import lru_cache
def rob_memo(nums: list[int]) -> int:
@lru_cache(maxsize=None)
def dp(i: int) -> int:
if i >= len(nums):
return 0
# Either skip house i, OR rob house i and jump to i + 2
return max(dp(i + 1), nums[i] + dp(i + 2))
return dp(0)- State:
i(current house index). - Base case:
i >= len(nums)→0loot remaining. - Transition:
max(skip, rob)=max(dp(i + 1), nums[i] + dp(i + 2)).
Approach B: Bottom-Up Tabulation & Space Compression
Dry-Run Trace: rob_bottom_up([2, 7, 9, 3, 1])
Step 1: Rob house 0 (+2)
max(skip=0, rob=0+2) = 2. Best so far = 2.
Notice dp[i] only reads the previous two states! Track prev2 (dp[i - 2]) and prev1 (dp[i - 1]):
House (val) | prev2 (before) | prev1 (before) | Choice max(prev1, prev2 + val) | prev2, prev1 (after) |
|---|---|---|---|---|
| Start | 0 | 0 | — | 0, 0 |
2 | 0 | 0 | max(0, 0 + 2) = 2 | 0, 2 |
7 | 0 | 2 | max(2, 0 + 7) = 7 | 2, 7 |
9 | 2 | 7 | max(7, 2 + 9) = 11 | 7, 11 |
3 | 7 | 11 | max(11, 7 + 3) = 11 | 11, 11 |
1 | 11 | 11 | max(11, 11 + 1) = 12 | 11, 12 |
Final answer: 12 (2 + 9 + 1), computed in O(n) time and O(1) extra space!
Step-by-Step DP Table Trace: min_coins([1, 2, 5], amount=6)
Here dp[t] = minimum coins needed to sum to t. Initialize dp[0] = 0 and all others to INF = amount + 1:
Total t | Try c = 1 (1 + dp[t-1]) | Try c = 2 (1 + dp[t-2]) | Try c = 5 (1 + dp[t-5]) | Final dp[t] |
|---|---|---|---|---|
0 | — | — | — | 0 |
1 | 1 + dp[0] = 1 | — | — | 1 |
2 | 1 + dp[1] = 2 | 1 + dp[0] = 1 | — | 1 |
3 | 1 + dp[2] = 2 | 1 + dp[1] = 2 | — | 2 |
4 | 1 + dp[3] = 3 | 1 + dp[2] = 2 | — | 2 |
5 | 1 + dp[4] = 3 | 1 + dp[3] = 3 | 1 + dp[0] = 1 | 1 |
6 | 1 + dp[5] = 2 | 1 + dp[4] = 3 | 1 + dp[1] = 2 | 2 (5 + 1) |
Edge Cases to Always Guard Against
- Zero target (
amount == 0):dp[0] = 0returns0coins immediately. - Unreachable target (
coins = [2], amount = 3):dp[3]remainsINF, soreturn dp[amount] if dp[amount] != INF else -1returns-1instead of a giant sentinel! - Empty input (
nums = []in House Robber):prev1 = 0returns0.
Python's @lru_cache hashes every argument to dp(...). Passing a list or set raises TypeError: unhashable type: 'list'. Keep nums in the outer function scope and pass only immutable integers/tuples like (i, rem) into dp(...)!
Start with Top-Down @lru_cache when state transitions are sparse or tricky (2D strings, intervals, trees). Switch to Bottom-Up when n >= 1,000 (to avoid Python's recursion limit) or when the interviewer asks to optimize space to O(1).
Try It Yourself in the Playground
Test House Robber (both Top-Down @lru_cache and O(1)-space Bottom-Up) and Coin Change (Minimum Coins) right below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why is greedy ("always pick the biggest coin first") wrong for min_coins([1, 3, 4], 6)?
Quick Checkpoints
What problem property makes @functools.lru_cache turn an exponential recursive solution into polynomial time?
Why might you convert a Top-Down @lru_cache DP function to Bottom-Up tabulation for huge inputs (n = 50,000)?
Why does min_coins initialize dp = [amount + 1] * (amount + 1) (with dp[0] = 0)?