Overlapping subproblems and memoization
Memoization stores each subproblem’s answer the first time it is computed. Repeated subtrees of the recursion tree collapse into cache hits.
Before you start: Recursion trees: Fibonacci and repeated work, Hash sets and maps in practice: counting, lookup, deduplication.
The idea
The textbook fib(5) makes 15 calls. The marked subtrees redo work the left side already did.
Each call to fib(n) starts two more calls. The tree roughly doubles with every level, but it only ever asks about n + 1 different values.
Intuition
fib(3) on the left and fib(3) on the right ask the same question. Both get the answer 2.
fib has no side effects and depends only on n. Two calls with the same n always return the same value. Subproblems that repeat like this are called overlapping subproblems.
Write each answer in a memo the first time. Later calls read it, so whole subtrees shrink to one lookup.
A memo is a map from arguments to answers. A hash map gives O(1) lookups, so a cache hit costs about as much as one call.
Complexity
Without a memo the calls grow like 1.6ⁿ. With a memo fib(n) makes 2n − 1 calls, so it runs in O(n).
Each n from 2 to the top recurses once and stores its value. Every other call is a base case or a hit, which costs O(1). For n = 40 that is 79 calls instead of about 330 million.
The memo holds one entry per n, so it takes O(n) space. The call stack also grows up to n frames deep.
Pitfalls
sum_from(i) adds nums[i:], but this memo was kept from nums = 4 5 6. It answers 15 for the new nums 1 1 1, so start a fresh memo for every input.
In Python, def f(i, memo={}) creates the dict once and shares it across all calls. That is fine for fib, where the answer depends on n only. It breaks when the answer also depends on a list that changes between calls.
A memo removes repeated work, not recursion depth. fib(10000) still nests 10,000 calls and overflows the stack.
Python stops at about 1,000 nested calls by default. The fix is to fill a table bottom-up from small n, which needs no recursion at all.
Variations
Tabulation fills the same answers bottom-up in a table. It does the same work in a loop, with no call stack.
Any pure function of small arguments can be memoized. Grid paths use the pair (r, c) as the key.
Code
Pseudocode
memo ← empty map
fib(n):
if n < 2: return n
if n in memo: return memo[n]
value ← fib(n - 1) + fib(n - 2)
memo[n] ← value
return value
Python
def fib(n, memo=None):
if memo is None:
memo = {}
if n < 2:
return n
if n in memo:
return memo[n]
value = fib(n - 1, memo) + fib(n - 2, memo)
memo[n] = value
return value
JavaScript
function fib(n, memo = new Map()) {
if (n < 2) return n;
if (memo.has(n)) return memo.get(n);
const value = fib(n - 1, memo) + fib(n - 2, memo);
memo.set(n, value);
return value;
}
Java
static long fib(int n, Map<Integer, Long> memo) {
if (n < 2) return n;
if (memo.containsKey(n)) return memo.get(n);
long value = fib(n - 1, memo) + fib(n - 2, memo);
memo.put(n, value);
return value;
}
Practice problems (6)
Memoized Fibonacci Warm-up
Return the n-th Fibonacci number: fib(0) = 0, fib(1) = 1 and fib(n) = fib(n - 1) + fib(n - 2).
The plain recursive version makes billions of calls for n = 50. Add a memo so every n is computed once.
Calls with and without memo Warm-up
Count the calls fib(5) makes, first by the plain rule and then with a memo. Answer each question before the trace plays. Every call counts, base cases and memo hits included.
Which calls hit the cache Standard
The trace builds the full call tree of fib(5) without a memo. Now imagine the same code with a memo, filled left to right as the calls return.
Click every call in the tree that the memo version would answer straight from the memo. Calls inside a subtree the memo skips are never made, so they are not hits.
Climbing stairs with a memo Standard
A staircase has n steps. Each move climbs 1 step or 2 steps. Return the number of different move sequences that reach the top.
Write it as a recursive function with a memo. The last move was either 1 step or 2 steps, so ways(n) = ways(n - 1) + ways(n - 2).
Fewest steps to one Standard
Start from a positive integer n. In one step you may subtract 1, divide by 2 if the number is even, or divide by 3 if it is divisible by 3. Return the fewest steps that reach 1.
Dividing whenever possible is not always best: from 10, halving gives 10 → 5 → 4 → 2 → 1 (4 steps), but 10 → 9 → 3 → 1 takes 3.
Memoized grid paths Challenge
A robot starts in the top-left cell of obstacleGrid and wants the bottom-right cell. It may only move right or down. Cells with 1 are obstacles; cells with 0 are open.
Return the number of different paths. Solve it top-down: paths(r, c) is the number of paths into cell (r, c), and it equals paths(r - 1, c) + paths(r, c - 1). Memoize on the pair (r, c).
Related topics
Next on the path: Tabulation: filling the table bottom-up