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

6 min readUpdated 2026-11-30
In This Lesson
  • 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) and dp(4) are recomputed exponentially many times → O(2ⁿ) (completely stalls at n = 45!).
  • DP (Memoization or Tabulation): Each state i from 0 to n - 1 is solved once → O(n) time (and O(1) space when compressed!).

When Does DP Apply? (2 Tell-Tale Clues)

  1. Optimization or Counting: The prompt asks for "minimum cost", "maximum profit", "longest sequence", or "number of ways"—and greedy fails!
  2. 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):

python
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) → 0 loot 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])

Interactive Walkthrough: House Robber Bottom-Up DPStep 1 / 5
H[0]$2
H[1]$7
H[2]$9
H[3]$3
H[4]$1
prev2 = 0prev1 (best) = 2

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)
Start00—0, 0
200max(0, 0 + 2) = 20, 2
702max(2, 0 + 7) = 72, 7
927max(7, 2 + 9) = 117, 11
3711max(11, 7 + 3) = 1111, 11
11111max(11, 11 + 1) = 1211, 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 tTry 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
11 + dp[0] = 1——1
21 + dp[1] = 21 + dp[0] = 1—1
31 + dp[2] = 21 + dp[1] = 2—2
41 + dp[3] = 31 + dp[2] = 2—2
51 + dp[4] = 31 + dp[3] = 31 + dp[0] = 11
61 + dp[5] = 21 + dp[4] = 31 + dp[1] = 22 (5 + 1)

Edge Cases to Always Guard Against

  • Zero target (amount == 0): dp[0] = 0 returns 0 coins immediately.
  • Unreachable target (coins = [2], amount = 3): dp[3] remains INF, so return dp[amount] if dp[amount] != INF else -1 returns -1 instead of a giant sentinel!
  • Empty input (nums = [] in House Robber): prev1 = 0 returns 0.
Never Pass Mutable Lists Into @lru_cache

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(...)!

How to Tell Top-Down vs Bottom-Up Apart in Interviews

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:

Python 3Try It Live: House Robber & Coin Change DP
Output

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

Check Your Understanding

What problem property makes @functools.lru_cache turn an exponential recursive solution into polynomial time?

Check Your Understanding

Why might you convert a Top-Down @lru_cache DP function to Bottom-Up tabulation for huge inputs (n = 50,000)?

Check Your Understanding

Why does min_coins initialize dp = [amount + 1] * (amount + 1) (with dp[0] = 0)?