Cache repeated subproblems to turn exponential time into polynomial time.
Use it when the same call, with the same arguments, is made many times. Signal words: count the ways, the best of, the same subproblem again.
Spot draw the calls, and look for equal arguments in different branches.
Key name every argument that changes the answer, and nothing else.
Look up check the cache before any work, and return a stored answer at once.
Store save the answer under the key before you return.
Cost the number of different keys times the work for one key, plus the memory for the keys.
In this lesson you learn to spot a recursion that repeats the same call, and to fix it with a cache. You see real call counts before and after, and the one rule that keeps the cache correct.
You work on the game feed of a social app. A player climbs a ladder of badge levels from level 0 to level n. Each step goes up 1 level or 2 levels.
Your team lead says: How many different sequences of steps reach level
n? The ladder can have 50 levels.
Here is a short check for level 4. There are 5 sequences: 1 1 1 1, 1 1 2, 1 2 1, 2 1 1 and 2 2.
So the task is this: count the sequences for any n, and keep the work small.
A student works through a long sum that needs the same smaller sums again and again. After solving one, the student writes it in a notebook.
Before solving any smaller sum, the student looks in the notebook. If the answer is there, the student copies it and moves on.
The notebook is the cache. Looking before solving is the cache check. Writing after solving is the cache store.
A student writes each solved sum in a notebook, and looks there before solving a smaller sum again.
Before you write code, count the sequences for level 5 by hand, with a notebook. Solve each level from the two levels below it. Write the answer for a level in the notebook, and look there first.
Solve it by hand: Five levels, with a cache. The hand-solve sheet loads in your browser.
Level 0 and level 1 each have one way. Every higher level adds the ways of the level below it and the level two below it.
Each row is a level, in the order the notebook fills.
| Level | Ways | How it is found |
|---|---|---|
| 0 | 1 | base case |
| 1 | 1 | base case |
| 2 | 2 | level 1 plus level 0 |
| 3 | 3 | level 2 plus level 1 |
| 4 | 5 | level 3 plus level 2 |
| 5 | 8 | level 4 plus level 3 |
The recursion made 9 calls. Levels 2 and 3 were each read from the cache once, so 2 of the 9 calls were cache hits.
Start with a correct version. It counts the sequences of level n as the sequences of level n - 1 plus level n - 2.
def ways_to_climb(n):
if n <= 1: # levels 0 and 1 have one way each
return 1
return ways_to_climb(n - 1) + ways_to_climb(n - 2)This is correct. The team keeps it as the reference. The question is how it behaves when the ladder grows.
Now check the real size.
The ladder can have 50 levels.
Run the function, in Python, and count its calls:
Predict the repeats
Q For 35 levels the first attempt makes 29,860,703 calls, but the ladder has only 36 different levels. About how many calls does it make for each different level?
Answer: C
There are 29,860,703 calls and 36 different levels. The ratio is 829,464, so the same level is solved again and again.
The first attempt is correct, and most of its calls repeat an answer it already found. A notebook can remove the repeats.
Draw the calls for level 5 as a tree. The call for level 3 appears twice. The call for level 2 appears three times. Each copy of a call solves the same problem.
The plain recursion for 5 levels makes 15 calls for 6 different levels, and level 2 is solved 3 times.
Here is how many times each level is called for level 5. Every number is a count from running the first attempt.
| Level | Times it is called |
|---|---|
| 5 | 1 |
| 4 | 1 |
| 3 | 2 |
| 2 | 3 |
| 1 | 5 |
| 0 | 3 |
The total is 15 calls for 6 different levels. A call that repeats an earlier call has the same arguments, and so it has the same answer. Store the answer the first time, and every repeat becomes a lookup.
With a cache, level 5 needs 9 calls instead of 15. Now compare the two versions for longer ladders.
Race: Calls to climb n levels, counted by running both versions. The operation counter loads in your browser.
The race counts the calls of both versions for 10 to 30 levels. For 30 levels the plain recursion makes 2,692,537 calls and the cached one makes 59. For 40 levels the cached one makes 79, and for 50 levels it makes 99.
The call is ways_to_climb(6). The player stops at five steps and asks you to predict.
Dry run: Predict each step: six levels, with a cache. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row. The row is a level that is read from the cache, in order.
| Hit number | Level read from the cache | Calls so far |
|---|---|---|
| 1 | 2 | 9 |
| 2 | 3 | 10 |
| 3 | 4 | 11 |
The recursion makes 11 calls for 6 levels, where the plain recursion makes 25. The answer is 13.
Exercise · Predict the output: Which levels does the cached search call?. Each call prints its level as it starts, before it looks in the cache. What does `climb(5, {})` print?
def climb(level, cache):
print(level)
if level <= 1:
return 1
if level in cache:
return cache[level]
ways = climb(level - 1, cache) + climb(level - 2, cache)
cache[level] = ways
return ways
climb(5, {})With a cache, each different level is solved once. The cost is the number of different subproblems times the work for each one. For the ladder, that is about n levels with constant work, so 50 levels need 99 calls.
A table filled from level 0 upwards does the same job without recursion. That is dynamic programming, and the module a6-dynamic-programming/dp-from-recursion teaches it.
Here is the rule that keeps the cache correct. Every line of the templates exists to protect it.
A cache entry is stored only after its answer is computed, and its key holds every argument that can change the answer.
If the key leaves out an argument that matters, two different problems share one entry, and one of them gets a wrong answer. If the answer is stored late or never, the cache only wastes memory.
Use it when the same call, with the same arguments, is made many times. Signal words: count the ways, the best of, the same subproblem again.
Spot: draw the calls, and look for equal arguments in different branches.
Key: name every argument that changes the answer, and nothing else.
Look up: check the cache before any work, and return a stored answer at once.
Store: save the answer under the key before you return.
Cost: the number of different keys times the work for one key, plus the memory for the keys.
Each call is named by its level. Look in the cache before solving, and store the answer before returning.
def ways_to_climb(n):
return climb(n, {})
def climb(level, cache):
# [1] Base case: levels 0 and 1 each have exactly one way.
if level <= 1:
return 1
# [2] Cache hit: this level was solved before, so return the stored answer.
if level in cache:
return cache[level]
# [3] Solve the level from the two levels below it.
ways = climb(level - 1, cache) + climb(level - 2, cache)
# [4] Store the answer before returning, so the next call finds it.
cache[level] = ways
return wayspublic long waysToClimb(int n) {
return climb(n, new HashMap<>());
}
private long climb(int level, Map<Integer, Long> cache) {
// [1] Base case: levels 0 and 1 each have exactly one way.
if (level <= 1) {
return 1;
}
// [2] Cache hit: this level was solved before, so return the stored answer.
if (cache.containsKey(level)) {
return cache.get(level);
}
// [3] Solve the level from the two levels below it.
long ways = climb(level - 1, cache) + climb(level - 2, cache);
// [4] Store the answer before returning, so the next call finds it.
cache.put(level, ways);
return ways;
}long long climb(int level, unordered_map<int, long long>& cache) {
// [1] Base case: levels 0 and 1 each have exactly one way.
if (level <= 1) {
return 1;
}
// [2] Cache hit: this level was solved before, so return the stored answer.
auto found = cache.find(level);
if (found != cache.end()) {
return found->second;
}
// [3] Solve the level from the two levels below it.
long long ways = climb(level - 1, cache) + climb(level - 2, cache);
// [4] Store the answer before returning, so the next call finds it.
cache[level] = ways;
return ways;
}
long long waysToClimb(int n) {
unordered_map<int, long long> cache;
return climb(n, cache);
}function climb(level, cache) {
// [1] Base case: levels 0 and 1 each have exactly one way.
if (level <= 1) {
return 1;
}
// [2] Cache hit: this level was solved before, so return the stored answer.
if (cache.has(level)) {
return cache.get(level);
}
// [3] Solve the level from the two levels below it.
const ways = climb(level - 1, cache) + climb(level - 2, cache);
// [4] Store the answer before returning, so the next call finds it.
cache.set(level, ways);
return ways;
}
function waysToClimb(n) {
return climb(n, new Map());
}Exercise · Put it in order: Look first, store before returning. Arrange the lines into a cached climb. The cache is a list with one slot for each level, and 0 means that the level is not solved yet.
def climb(level, cache):
if level <= 1: return 1
if cache[level] != 0: return cache[level]
ways = climb(level - 1, cache) + climb(level - 2, cache)
cache[level] = ways
return ways
return climb(level - 1, cache) + climb(level - 2, cache)
cache[level] = 0Rebuild the template: put its lines back in order. Loads in your browser.
The answer for 5 levels is 8, and the recursion makes 9 calls. The plain recursion makes 15.
The cached climb checks the cache after the base case, solves the level from the two below it, and stores the answer before returning.
A robot on a street grid moves one block down or one block right. The number of routes for a pair of distances depends on both, so the key holds both.
def route_count(down, right):
return routes(down, right, {})
def routes(down, right, cache):
# [1] Base case: on a straight line there is exactly one route.
if down == 0 or right == 0:
return 1
# [2] Cache hit: this pair of distances was solved before, so return the stored answer.
key = (down, right)
if key in cache:
return cache[key]
# [3] Solve the pair from the two neighbours: one step down, or one step right.
total = routes(down - 1, right, cache) + routes(down, right - 1, cache)
# [4] Store the answer under both distances before returning.
cache[key] = total
return totalpublic long routeCount(int down, int right) {
return routes(down, right, new HashMap<>());
}
private long routes(int down, int right, Map<Integer, Long> cache) {
// [1] Base case: on a straight line there is exactly one route.
if (down == 0 || right == 0) {
return 1;
}
// [2] Cache hit: this pair of distances was solved before, so return the stored answer.
int key = down * 100 + right;
if (cache.containsKey(key)) {
return cache.get(key);
}
// [3] Solve the pair from the two neighbours: one step down, or one step right.
long total = routes(down - 1, right, cache) + routes(down, right - 1, cache);
// [4] Store the answer under both distances before returning.
cache.put(key, total);
return total;
}long long routes(int down, int right, unordered_map<int, long long>& cache) {
// [1] Base case: on a straight line there is exactly one route.
if (down == 0 || right == 0) {
return 1;
}
// [2] Cache hit: this pair of distances was solved before, so return the stored answer.
int key = down * 100 + right;
auto found = cache.find(key);
if (found != cache.end()) {
return found->second;
}
// [3] Solve the pair from the two neighbours: one step down, or one step right.
long long total = routes(down - 1, right, cache) + routes(down, right - 1, cache);
// [4] Store the answer under both distances before returning.
cache[key] = total;
return total;
}
long long routeCount(int down, int right) {
unordered_map<int, long long> cache;
return routes(down, right, cache);
}function routes(down, right, cache) {
// [1] Base case: on a straight line there is exactly one route.
if (down === 0 || right === 0) {
return 1;
}
// [2] Cache hit: this pair of distances was solved before, so return the stored answer.
const key = down * 100 + right;
if (cache.has(key)) {
return cache.get(key);
}
// [3] Solve the pair from the two neighbours: one step down, or one step right.
const total = routes(down - 1, right, cache) + routes(down, right - 1, cache);
// [4] Store the answer under both distances before returning.
cache.set(key, total);
return total;
}
function routeCount(down, right) {
return routes(down, right, new Map());
}Exercise · Find the bug: The route count that never ends. This counts the routes on a street grid with a cache. For some inputs it never returns. Which line is wrong?
def route_count(down, right):
return routes(down, right, {})
def routes(down, right, cache):
if down == 0 and right == 0:
return 1
key = (down, right)
if key in cache:
return cache[key]
total = routes(down - 1, right, cache) + routes(down, right - 1, cache)
cache[key] = total
return totalFor 3 blocks down and 3 right there are 20 routes. The plain recursion makes 39 calls, and the cached one makes 19. For 8 and 8 the plain recursion makes 25,739 calls and the cached one makes 129. For 12 and 12 the counts are 5,408,311 and 289.
Suppose a recursion has two arguments, down and right, and you build the key from down alone. Each call then finds an entry made for a different right. Every number below was measured by running both versions.
| Call | Correct answer | With the key down only |
|---|---|---|
route_count(2, 3) |
10 | 13 |
route_count(3, 3) |
20 | 40 |
The key must hold every argument that changes the answer. Here that is both distances.
The time is the number of different keys times the work for one key. The space is the number of keys. For the ladder, both are about n. The recursion depth is still n, so a very deep ladder needs a table filled in order instead.
Real production data brings edge cases.
For ways_to_climb(0) and ways_to_climb(1) the answer is 1. The base case answers them, and the cache is never used.
For ways_to_climb(70) the answer is 308,061,521,170,129. It is above 2^32, so use a 64-bit integer. It is below 2^53, so a JavaScript number holds it exactly. The cached recursion makes 139 calls.
Two calls, ways_to_climb(5) and ways_to_climb(6), can share one cache. The second call finds levels 2 to 5 already stored, and makes only 3 new calls. Share a cache only when the answer depends on the key alone.
For route_count(3, 3) the pairs (1, 2) and (2, 1) are different keys, even though they have the same answer. The cache stores both, and that is correct.
This version of the routes recursion builds the key from down alone.
Counterexample: route_count(3, 3) returns 40, but there are 20 routes. route_count(2, 3) returns 13, but there are 10.
The key must hold every argument that changes the answer.
With a cache key built from down alone, the routes for a 3 by 3 grid come out as 40, but the answer is 20.
This version looks in the cache, but it never stores the answer.
Counterexample: the answer for 30 levels is still right, 1,346,269. But the recursion makes 2,692,537 calls, the same as the plain version, because the cache stays empty.
Store the answer before every return that follows real work.
This version creates a new empty cache inside each call.
Counterexample: for 30 levels it makes 2,692,537 calls, the same as the plain version, because no call ever sees an earlier answer.
Create the cache once, outside the recursion, and pass it down.
Exercise · Break it: Find the pairs that share a key. This counts the routes on a grid with a cache whose key is down + right. Find a grid where it gives the wrong number of routes.
def route_count(down, right):
return routes(down, right, {})
def routes(down, right, cache):
if down == 0 or right == 0:
return 1
key = down + right
if key in cache:
return cache[key]
total = routes(down - 1, right, cache) + routes(down, right - 1, cache)
cache[key] = total
return totalThe skip-or-take recursion for 15 items makes 65,535 calls. Every call has a different list of chosen items, so a cache keyed by the position and the list finds 0 hits and stores 65,535 entries.
A halving recursion on 1,000,000 makes 20 calls, and none repeat. A cache would add memory and no speed. Memoise only when the same arguments come back.
Your team lead brings four product changes. Each one uses the same four steps.
Count the ways to climb a staircase with 1 or 2 steps at a time (LeetCode 70: Climbing Stairs).
Each term is the sum of the two before it (LeetCode 509: Fibonacci Number).
Each term is the sum of the three before it (LeetCode 1137: N-th Tribonacci Number).
Count the routes for a robot that moves right or down (LeetCode 62: Unique Paths).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain how a cache removes repeated calls, and what the key must hold. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
I draw the calls and look for the same arguments in different branches. If they repeat, I add a cache.
Before solving, I look in the cache. After solving, I store the answer under a key. The key holds every argument that changes the answer.
The cost is the number of different keys times the work for one key. If no call repeats, a cache only adds memory.
First I draw the calls and look for the same arguments in different branches. For a ladder of fifty levels the plain recursion makes more than forty billion calls, but there are only fifty-one different levels.
So I add a cache. Before solving, I look up the key. After solving, I store the answer under it. The key holds every argument that changes the answer.
Then each different problem is solved once. Fifty levels need ninety-nine calls. If no call repeats, I do not cache, because it adds memory and no speed. A table filled in order is the next step, and that is dynamic programming.
Checkpoint · Memoisation teaser
Q1/10 How do you spot a repeated subproblem?
Answer: B
Equal arguments in different branches mean the same answer is found more than once. A recursion with two calls can still have no repeats.
Q2/10 For 5 levels, how many calls does the plain recursion make, and how many does the cached one make?
Answer: B
The plain recursion makes 15 calls, and level 2 is solved 3 times. The cached one makes 9 calls, with 2 cache hits.
Q3/10 For 35 levels the plain recursion makes 29,860,703 calls, and the ladder has 36 different levels. About how many calls does it make for each different level?
Answer: C
The ratio is 29,860,703 divided by 36, which is about 829,000.
Q4/10 What does a memoised call do first?
Answer: B
The lookup comes before any work. A stored answer is returned without a recursive call.
Q5/10 When must the answer be stored?
Answer: C
Storing before the return means the next call with the same key finds the answer.
Q6/10 What must the cache key hold?
Answer: B
If the key leaves out an argument that matters, two different problems share one entry.
Q7/10 A routes recursion builds its key from down alone. What does route_count(3, 3) return?
Answer: C
The correct answer is 20. With the key down alone the run returns 40.
Q8/10 How many calls does the cached recursion make for 30 levels?
Answer: C
The cached recursion makes 59 calls. The plain recursion makes 2,692,537, and the answer is 1,346,269.
Q9/10 A cached version never stores its answers. How many calls does it make for 30 levels?
Answer: B
The answer is still right, but the cache stays empty, so no call is ever a hit.
Q10/10 The skip-or-take recursion for 15 items makes 65,535 calls. What would a cache keyed by the position and the chosen list find?
Answer: C
Every call has a different list of chosen items, so no key repeats. A cache would add memory and no speed.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Cache the repeated subproblem | Freight | Easy | Counting routes, and the calls before and after a cache |
| 2 | Climb the pricing tiers | Shop | Easy | The one-argument cache |
| 3 | Retry counts that follow a three-term rule | Observe | Easy | A cache for a three-term rule |
| 4 | When memoisation does not help | Stream | Medium | Counting distinct problems against calls |
| 5 | Binary codes with no two ones side by side | Rides | Medium | A cache of counts that guides a walk |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.