Lesson 2 · Unit 02
Remember answers
Memoization turns a tree back into a chain
What you practise
- A memo map
- Calls drop to O(n)
- Order of check, compute, store
Try a question from this lesson
Pick one
Plain fib(30) makes 2,692,537 calls. This version writes every answer down the first time. What does it print?
calls = 0
memo = {}
def fib(n):
global calls
calls += 1
if n < 2:
return n
if n not in memo:
memo[n] = fib(n - 1) + fib(n - 2)
return memo[n]
fib(30)
print(calls)let calls = 0;
const memo = new Map();
function fib(n) {
calls += 1;
if (n < 2) return n;
if (!memo.has(n)) {
memo.set(n, fib(n - 1) + fib(n - 2));
}
return memo.get(n);
}
fib(30);
console.log(calls);let calls = 0;
const memo = new Map<number, number>();
function fib(n: number): number {
calls += 1;
if (n < 2) return n;
if (!memo.has(n)) {
memo.set(n, fib(n - 1) + fib(n - 2));
}
return memo.get(n)!;
}
fib(30);
console.log(calls);Correct answer
59
Why
Each n from 2 to 30 is computed once, and each computation makes two calls: 29 × 2, plus the first call, is 59. Every other request is answered from the map without recursing.
Python noteA dict is the natural memo: n not in memo checks for the key and memo[n] reads it.
JavaScript noteA Map keeps number keys as numbers. A plain object would turn them into strings.
TypeScript noteMap<number, number> maps number keys to number values. get returns number | undefined, so the ! tells the compiler the key is there.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Memoization
Branching recursion repeats itself: the same input, the same answer, computed again.
Memoization keeps a map from input to answer. On each call: look in the memo first. On a miss, compute the answer, store it, then return it. On a hit, return what is stored and skip the whole subtree.
9 more exercises in the app
- 1× fill the blanks
- 2× type the answer
- 3× multiple choice
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.