In the Recursion lesson, fibonacci(30) took about 2.7 million calls, and the fix was promised here. The fix is simple: write down a function's results once they're calculated. If the function is called again with the same number, you just read the result from your notes.
This is called memoization. Memoization is one way of doing dynamic programming (DP): breaking a problem into sub-problems (smaller parts of the problem) that appear again and again, then solving each sub-problem only once. Memoization is like writing down how many pages a thick book has after you count them: if someone asks again, you just read your note. In code, that note is called a memo, and counting the pages is running the function.
The problem: work done twice
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, ... Each number is the sum of the two before it. In this lesson, fib(n) is the nth number of the sequence, so fib(5) = fib(4) + fib(3). But fib(4) needs fib(3) again, and so on. Before you look at the table, guess: while calculating fib(5), how many times is the plain recursive fib called, 5, 9 or 15? This table shows how many times each call happens while calculating fib(5):
| Call | Times calculated |
|---|---|
fib(5) |
1 |
fib(4) |
1 |
fib(3) |
2 |
fib(2) |
3 |
fib(1) |
5 |
fib(0) |
3 |
That's 15 calls in total, though only 6 calls are different. This code counts those calls:
let calls = 0;
function fib(n) {
calls++;
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2); // two branches, worked out again and again
}
console.log(fib(5)); // 5
console.log(calls); // 15
callscounts how many timesfibruns:calls++adds 1 on every call.if (n <= 1) return n;is the base case:fib(0)= 0,fib(1)= 1.- Every call branches in two,
fib(n - 1)andfib(n - 2), and many branches calculate the same thing.
The number of calls grows about 1.6 times each time n goes up by 1. fib(40) takes about 331 million calls, enough to freeze the browser for about a second.
The memo: write it down, then reuse it
This is the same fib, with notes called memo added:
const memo = {};
function fib(n) {
if (n <= 1) return n;
if (n in memo) return memo[n]; // worked out before: read it from the notes
memo[n] = fib(n - 1) + fib(n - 2); // work it out once, then write it down
return memo[n];
}
console.log(fib(40)); // 102334155, straight away
memois a plain object for the notes: its keys aren, and its values are the result offib(n).n in memoistruewhen the keynis already inmemo.memo[n] !== undefinedworks too.- The order matters: check the notes before calculating, and store in
memo[n]after calculating.
With a memo, each fib(k), for k from 0 to 40, is calculated only once: 41 calculations, down from 331 million calls. So the steps are O(n). This lesson's Lab calls the notes a cache, and uses a Map to store them (memo.has(n), memo.get(n), memo.set(n, result)). A Map is a special object for key and value pairs, and as a memo it works exactly like a plain object.
In the exercise, the notes are passed as a parameter with a default value: function fibMemo(n, memo = {}). The default {} is only used when no memo is passed, which is on the first call. So that every call shares the same notes, keep passing memo along: fibMemo(n - 1, memo).
A table: from small to big
Memoization is also called top-down DP: start from the big problem, then go down to smaller problems through recursion. The other way is bottom-up, or tabulation: fill a table from the smallest case with a plain loop. This is Fibonacci with tabulation:
function fibTable(n) {
const dp = [0, 1];
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
console.log(fibTable(10)); // 55
dp is the table, an array, and dp[i] holds fib(i). Each entry is calculated from the two entries before it, which are already filled. This way uses no recursion, so there's no risk of a stack overflow for big n. DP only helps when sub-problems repeat, like fib(3), which was calculated twice in the first table. If every sub-problem appears only once, the notes only take up memory.
Tabulation also solves a more practical problem: the fewest coins needed to pay an amount. For example, paying 6 with coins of 4, 3 and 1, where each coin can be used many times. dp[x] is the fewest coins for the amount x. For each coin c that fits (is not more than x), pay c first. What is left is x - c, and the answer for that is already in the table. Of all the coins c, take the smallest dp[x - c] + 1: the coins for what is left, plus one coin c:
function minCoins(amount, coins) {
const dp = [0]; // dp[x] = fewest coins for the amount x
for (let x = 1; x <= amount; x++) {
dp[x] = Infinity; // no way found yet
for (const c of coins) {
if (c <= x) dp[x] = Math.min(dp[x], dp[x - c] + 1);
}
}
return dp[amount];
}
console.log(minCoins(6, [4, 3, 1])); // 2
Each dp[x] starts as Infinity, so the first way to pay that the loop finds always replaces it. dp after the loop:
| x | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
dp[x] |
0 | 1 | 2 | 1 | 1 | 2 | 2 |
dp[6] = 2, which is 3 + 3: dp[6 - 3] = dp[3] = 1, plus one coin of 3. For an amount n and k kinds of coin, there are n × k steps, so O(n × k). In the Greedy Algorithm lesson later, you will see that a simpler way (take the biggest coin first) fails on this problem.
⚠️ Notes that never get used
- Not passing the memo along.
fibMemo(n - 1)withoutmemogives each call new, empty notes, so the function is slow again. WritefibMemo(n - 1, memo). - Checking the notes after the work. If
fib(n - 1) + fib(n - 2)runs first andmemois checked afterwards, the heavy work is already done. - Checking with
if (memo[n]). A stored result can be 0, andifreads 0 asfalse(falsy). So that result is calculated again. Usen in memoormemo[n] !== undefined.
TL;DR: Memoization writes down a function's results, once calculated, in a memo object (or a Map). Check memo first. If the result isn't there, calculate it, then store it in memo[n]. Plain recursive Fibonacci (each number is the sum of the two before it) calculates the same things again and again: fib(40) takes about 331 million calls. With a memo, each fib(k) is calculated once, so it's O(n). If the memo is a parameter, keep passing it to every call. Tabulation (bottom-up) fills a table from small cases to big ones with a loop. Memoization and tabulation are both ways of doing dynamic programming (DP), which helps when sub-problems (smaller parts of the problem) repeat.
⚡ Work done twice
Guess first: fib(n) calculates the nth Fibonacci number with recursion, fib(n - 1) + fib(n - 2). For fib(5), how many times is this plain recursive version called: 5, 9 or 15?
15 times, though only 6 calls are different (fib(0) to fib(5)). fib(2) alone is calculated 3 times.
Meaning: Every call branches in two, fib(n - 1) and fib(n - 2), and many branches calculate the same thing. fib(40) takes about 331 million calls.
⚡ The memo: write it down, then reuse it
Write:
const memo = {};
function fib(n) {
if (n <= 1) return n;
if (n in memo) return memo[n]; // worked out before: read it from the notes
memo[n] = fib(n - 1) + fib(n - 2); // work it out once, then write it down
return memo[n];
}
console.log(fib(40)); // 102334155, straight away
Meaning: memo is the notes: an object that stores the result of fib(n) under the key n. This is called memoization. Check the notes before calculating, and store in memo[n] after. Each fib(k), for k from 0 to 40, is calculated only once: 41 calculations, so O(n).
⚡ A table: from small to big
Write:
function fibTable(n) {
const dp = [0, 1];
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
Meaning: Tabulation (bottom-up) fills the table dp from the smallest case with a plain loop: dp[i] holds fib(i). There's no recursion, so no risk of a stack overflow. Memoization and tabulation are ways of doing dynamic programming (DP), and DP only helps when sub-problems (smaller parts of the problem) repeat.