← All animations

🧠 Memoization & Dynamic Programming

Some recursive problems solve the same little subproblem over and over — so the naive version does an astronomical amount of redundant work. The fix is almost embarrassingly simple: remember answers you've already computed. That single idea — caching overlapping subproblems — is the heart of dynamic programming, and it can turn an O(2ⁿ) algorithm into a linear one. Watch a Fibonacci call tree explode, then collapse.

1. The naive recursion explodes

To compute fib(n), the naive definition calls fib(n−1) + fib(n−2) — and each of those splits again, all the way down to fib(1) and fib(0). The trouble: the same subproblems are recomputed many times. fib(2) alone gets recalculated again and again. The total number of calls is exactly 2·fib(n+1) − 1, which grows roughly like O(2ⁿ).

0 calls fib(8) = ?

2. Memoize it — the tree collapses

Now keep a cache. The first time we compute fib(k) we store it; every later request for the same k is a cache HIT (flashing green) — we return the saved value instantly and never re-expand that branch. The exponential tree collapses to one unique call per value: about n + 1 real computations. Same answer, dramatically less work.

Naive recursion

—
total calls · O(2ⁿ)

Memoized (top-down)

—
unique computations + cache hits · O(n)
0 unique · 0 hits
Bottom-up tabulation. Same answers, no recursion at all: fill a DP table left to right. Each cell dp[i] = dp[i−1] + dp[i−2] uses only the two before it, so one left-to-right sweep finishes the job in O(n) time.
dp[0..n] — bottom-up

3. When does this work? The two DP ingredients

Dynamic programming applies whenever a problem has both of these properties:

Overlapping subproblems. The recursion keeps asking the same smaller questions (fib(3) appears all over the naive tree). Caching each answer once removes the redundancy — that's what scene 2 did.
Optimal substructure. The answer to the whole is built from answers to its parts (fib(n) is literally fib(n−1) + fib(n−2)). So solving subproblems and combining them solves the original.

Top-down (memoization) writes the natural recursion and adds a cache, computing subproblems lazily — only the ones you actually need. Bottom-up (tabulation) drops recursion and fills a table in dependency order. Both run in O(n) here; the difference is style and call-stack vs table.

The trade-off is time vs space: the cache costs extra memory, but it buys back an exponential amount of recomputation. (And Fibonacci needs only the last two values, so its table can shrink to O(1) space.)

The same pattern powers many classic problems:

Grid paths (count routes) Coin change (fewest coins) Edit distance (Levenshtein) Knapsack Longest common subsequence Rod cutting