Suppose you count the ways to climb a staircase of n steps, where each move takes 1 step or 2. The last move was either 1 step or 2, so the count for n is the count for n − 1 plus the count for n − 2. Save that rule as opening-slow.ts:
// Opening problem: how many ways can you climb n steps, taking 1 or 2 steps at a time?
// The slow version: node opening-slow.ts
import { bench } from "./bench.ts";
// Plain recursion: the last move was 1 step or 2 steps. Every call makes two more calls, so
// it's O(phi^n) time (phi is about 1.618) and O(n) memory for the call stack.
export function waysSlow(n: number): number {
if (n <= 1) return 1; // 0 steps: one way (do nothing); 1 step: one way
return waysSlow(n - 1) + waysSlow(n - 2);
}
if (process.argv[1] === import.meta.filename) {
console.log([0, 1, 2, 3, 4, 5, 10].map((n) => `ways(${n}) = ${waysSlow(n)}`).join(", "));
bench("waysSlow", [30, 35, 40], (n) => n, waysSlow);
}
In one run, it took about 1.1 seconds for 40 steps, and every 5 more steps made it about 11 times slower.
The function is correct, but it asks the same question millions of times. This module teaches dynamic programming, which answers each question once and reuses the answer.
After this module, you can:
- count the calls of a recursive function and spot the smaller problems it solves again and again
- store each answer once, from the top down with a
Mapor from the bottom up with a table - find the state of a problem, the few numbers that decide the rest of the answer, and say what it costs
- keep only the last row of a table, and fill it in the direction that keeps it correct
Measure the slow count
Make a folder for the module, as in Module 1, and copy bench.ts into it unchanged:
mkdir module-11 && cd module-11 && echo '{ "type": "module" }' > package.json
bench.ts runs each size five times and prints the median, the middle one of the five times.
Pause and predict. waysSlow takes about 100 ms for 35 steps. How long does it take for 40? And for 60?
Here is what node opening-slow.ts printed:
ways(0) = 1, ways(1) = 1, ways(2) = 2, ways(3) = 3, ways(4) = 5, ways(5) = 8, ways(10) = 89
waysSlow
n median ms x prev
30 9.35
35 102.86 11.0
40 1144.30 11.1
Every table in this module comes from one run on an Intel Core i7-9750H laptop (x86_64, 6 cores, macOS) with Node.js 26.13.1. Your numbers will differ, but the ratios should look alike.
Why does each step cost so much more? Each call makes two more calls, until n is 0 or 1. Those two inputs are the base cases, the inputs small enough to answer without another call.
call-count.ts counts the calls, with a counter added to a copy of waysSlow:
n ways(n) calls (slow) 2 * ways(n) - 1 calls (memo)
5 8 15 15 9
10 89 177 177 19
20 10,946 21,891 21,891 39
30 1,346,269 2,692,537 2,692,537 59
35 14,930,352 29,860,703 29,860,703 69
40 165,580,141 331,160,281 331,160,281 79
waysSlow(30) solves n = 29 once, n = 20 89 times, n = 10 10,946 times, n = 2 514,229 times
phi = 1.618034, phi^5 = 11.09, phi^20 = 15,127
calls for n = 60: 2 * ways(60) - 1 = 5,009,461,563,921
The last column belongs to a later section. The slow calls are always 2 · ways(n) − 1, so the time grows like the count itself.
Each count is close to the one before times 1.618. That number is the golden ratio, written φ (phi). So waysSlow is O(φⁿ) time, and five more steps multiply it by φ⁵ ≈ 11.09. In other words, every 5 steps make it about 11 times slower, and the rows grew 11.0 and 11.1 times.
At 40 steps, each call took about 1,144.30 ms / 331,160,281 ≈ 3.5 ns. For 60 steps, 5.0 × 10¹² calls at that speed take about 17,300 seconds, close to 5 hours (not run). The memory is O(n), for the longest chain of calls that wait on each other.
Rule: When a recursive function calls itself more than once per call, count its calls before you time it. Two calls per level give exponential growth.
The same question, asked again and again
Figure 1 shows every call of waysSlow(5), as trace-demo.ts prints it. A call marked “again” asks a question that an earlier call already answered.
ways(5)
+-- ways(4)
| +-- ways(3)
| | +-- ways(2)
| | | +-- ways(1)
| | | `-- ways(0)
| | `-- ways(1)
| `-- ways(2) (again)
| +-- ways(1)
| `-- ways(0)
`-- ways(3) (again)
+-- ways(2) (again)
| +-- ways(1)
| `-- ways(0)
`-- ways(1)
15 calls for 8 ways
Figure 1: ways(3) is solved twice and ways(2) three times, and each repeat redoes its whole subtree.
A subproblem is the same question on a smaller input, here ways(k) for some k below n. A recursion has overlapping subproblems when it solves the same subproblem many times. In waysSlow(30), the subproblem n = 2 was solved 514,229 times.
But waysSlow(n) has only n + 1 different subproblems, 0 to n. Dynamic programming solves each subproblem once, stores its answer, and builds bigger answers from the stored ones. It applies when both of these hold:
- The answer can be built from the answers of smaller subproblems.
- Those subproblems overlap.
The next two sections show the two ways to write it.
Rule: Count the different subproblems, not the calls. If there are far fewer subproblems than calls, store the answers.
Store each answer once, from the top down
The smallest change to waysSlow is a Map from n to its answer. Before a call computes anything, it looks in the Map, and after it computes an answer, it stores it there. Storing answers this way is memoization, and the Map that holds them is the memo.
This style starts from the question you want answered and recurses down to smaller ones, so it is called top down. Here is waysMemo, an excerpt of opening-fast.ts in the lab folder:
// Top down: the slow recursion plus a Map from n to its answer.
// Each n from 2 to n is computed once: O(n) time, O(n) memory for the Map and the call stack.
export function waysMemo(n: number, memo = new Map<number, number>()): number {
if (n <= 1) return 1;
const known = memo.get(n);
if (known !== undefined) return known;
const result = waysMemo(n - 1, memo) + waysMemo(n - 2, memo);
memo.set(n, result);
return result;
}
The rest of opening-fast.ts holds the next section’s two functions and the code that checks and times all three. Compared with waysSlow, waysMemo adds three lines:
memo.get(n)looks up n.return knownreturns a stored answer.memo.set(n, result)stores a new one.
The Map is created once, as a default argument, and every call passes it down, so all calls share it. The check is known !== undefined, not if (known). That matters when an answer can be 0, as a mistake later in this module shows.
Pause and predict. waysSlow(40) made 331,160,281 calls. How many calls does waysMemo(40) make?
Figure 2 traces waysMemo(5), as trace-demo.ts prints it.
ways(5): not in the memo, solve it
ways(4): not in the memo, solve it
ways(3): not in the memo, solve it
ways(2): not in the memo, solve it
ways(1) = 1, base case
ways(0) = 1, base case
store ways(2) = 2
ways(1) = 1, base case
store ways(3) = 3
ways(2) = 2, from the memo
store ways(4) = 5
ways(3) = 3, from the memo
store ways(5) = 8
9 calls
Figure 2: the first path goes straight down to the base cases, and every later call for 2 or 3 finds its answer in the memo.
Each n from 2 to 5 is solved once and looked up at most once more. The last column of the call-count.ts table counted the calls: 2n − 1, so 79 for 40 steps instead of 331,160,281. Each call does O(1) work besides its two calls, so waysMemo is O(n) time. It uses O(n) memory for the Map and for the chain of calls, which still goes n levels deep.
node opening-fast.ts first checks the fast versions against waysSlow and against each other. Here is the first part of what it printed, with the memo’s rows:
ways(40): 165580141 165580141 165580141
ways(60): 2504730781961
waysMemo, same sizes as waysSlow
n median ms x prev
30 0.00
35 0.00 1.1
40 0.00 1.0
waysMemo
n median ms x prev
1,000 0.05
2,000 0.10 2.1
4,000 0.21 2.0
The count for 60 steps, which the slow version would need about 5 hours for, came back at once. At 40 steps, the memo took less than 0.005 ms, against 1,144.30 ms without it. Figure 3 draws the rows they share.
median ms for the ways to climb n steps (each # is about 26 ms)
n = 30 no memo | 9.35
memo | 0.00
n = 35 no memo #### 102.86
memo | 0.00
n = 40 no memo ############################################ 1144.30
memo | 0.00
Figure 3: without the memo the time grew 11 times per 5 steps, and with it the time is too small for bench.ts to show.
The waysMemo rows from 1,000 to 4,000 steps doubled with n, as O(n) predicts.
Rule: A memo turns a recursion into one computation per subproblem. Its cost is the number of subproblems times the work each one does.
Fill a table from the bottom up
The memo still recurses n levels deep, and that has a limit. Each call that waits for an answer keeps a stack frame, a small block of memory for its arguments and local variables. The frames of all waiting calls make up the call stack, and Module 6 showed that Node.js stops a recursion when it is full.
stack-depth.ts finds the largest n waysMemo handles, with each try in a fresh process:
most steps waysMemo handles, cold: 6,911
most steps waysMemo handles, warm: 9,569
waysMemo(100000): RangeError: Maximum call stack size exceeded
waysTable(100000): Infinity
So waysMemo stops somewhere between about 7,000 and 9,500 steps. The two limits differ because of how Node.js compiles the function, which “Going deeper” explains.
The fix is to turn the order around. Bottom up means you compute the smallest subproblems first, in an order where every answer a subproblem needs is ready before it. For the steps, that order is 0, 1, 2 and so on up to n.
Here are waysTable and waysTwoVars, an excerpt of opening-fast.ts:
// Bottom up: fill a table from the smallest n. O(n) time, O(n) memory, no recursion.
export function waysTable(n: number): number {
const table = new Array<number>(n + 1);
table[0] = 1;
table[1] = 1;
for (let i = 2; i <= n; i++) table[i] = table[i - 1] + table[i - 2];
return table[n];
}
// Bottom up, keeping only the last two answers. O(n) time, O(1) memory.
export function waysTwoVars(n: number): number {
let before = 1; // ways(i - 2)
let last = 1; // ways(i - 1)
for (let i = 2; i <= n; i++) [before, last] = [last, before + last];
return last;
}
waysTable fills an array in that order, with no recursion and no Map. Figure 4 shows the array for 6 steps, as trace-demo.ts prints it, and the two values that waysTwoVars keeps instead.
index 0 1 2 3 4 5 6
ways 1 1 2 3 5 8 13
i before last
- 1 1 start: ways(0), ways(1)
2 1 2
3 2 3
4 3 5
5 5 8
6 8 13
Figure 4: each entry reads only the two entries before it, so after it’s filled, everything left of those two is never read again.
waysTable is O(n) time and O(n) memory. waysTwoVars keeps the last two answers in two variables, before and last, so it’s O(n) time and O(1) memory. Neither one recurses, so waysTable(100000) returned where waysMemo(100000) threw.
Why did it return Infinity? The count of ways passes the largest finite JavaScript Number at 1,476 steps. Past that, the result is Infinity, but each call still does the same additions, so the timing is still fair.
The rest of the opening-fast.ts output times the two bottom-up versions:
waysTable
n median ms x prev
100,000 0.66
1,000,000 3.41 5.2
10,000,000 76.25 22.4
waysTwoVars
n median ms x prev
100,000 0.45
1,000,000 3.26 7.3
10,000,000 27.95 8.6
waysTwoVars grew 7.3 and 8.6 times for each 10 times more steps, close to O(n). waysTable grew 22.4 times at the last step. Its table for 10,000,000 steps is about 80 MB of new memory on every call, and “Going deeper” looks at that cost.
Rule: Bottom up, fill the answers from the smallest subproblem in an order where each one’s inputs are ready. Then keep only the answers that later entries still read.
Find the state
The steps problem had an obvious subproblem. Most problems don’t, so the real work is choosing what to store.
Module 10 listed every team of candidates whose daily costs fit a budget. Suppose you only need to know how many teams there are. Here are Module 10’s four candidates again, with costs in hundreds so that every amount fits on a line. Ana costs 3, Bo 2, Cy 5 and Di 4, and the budget is 7.
Walk the candidates in their order, and at each one either take it or skip it. Once you’ve decided on the first i candidates, the rest of the count doesn’t depend on who you took. It depends only on which candidate is next and how much money is left.
Those two numbers are the state. The state of a subproblem is the smallest set of values that decides its answer, whatever choices led to it. Figure 5 labels each choice with its state (next, left), as trace-demo.ts prints it.
(0, 7)
take Ana: (1, 4)
take Bo: (2, 2)
skip Cy: (3, 2)
skip Di: (4, 2)
skip Bo: (2, 4)
skip Cy: (3, 4)
take Di: (4, 0)
skip Di: (4, 4)
skip Ana: (1, 7)
take Bo: (2, 5)
take Cy: (3, 0)
skip Di: (4, 0) (again)
skip Cy: (3, 5)
take Di: (4, 1)
skip Di: (4, 5)
skip Bo: (2, 7)
take Cy: (3, 2) (again)
skip Di: (4, 2) (again)
skip Cy: (3, 7)
take Di: (4, 3)
skip Di: (4, 7)
9 leaves: 8 teams and the empty team
Figure 5: taking Ana and Bo leaves 2, and so does taking only Cy, so both paths reach the state (3, 2) and count the same teams below it.
With four candidates the repeats are few. But n candidates and a budget of B give only n · (B + 1) states, while the tree can have 2ⁿ leaves. So the overlap grows with n.
Write teams(i, left) for the number of teams, the empty one included, that candidates i to n − 1 can form with left to spend. Candidate i is either skipped or taken, if it fits:
teams(i, left) = teams(i + 1, left) + teams(i + 1, left − cost[i]), where the second term counts only when cost[i] ≤ left.
A formula like this, which gives a subproblem’s answer from the answers of smaller subproblems, is a recurrence. Its base case is teams(n, left) = 1, because with no candidates left, only the empty team remains. The answer is teams(0, budget) − 1, because the empty team doesn’t count.
Here is the recurrence with a memo and in a table, an excerpt of teams-count.ts. Candidate is Module 10’s type, a name and a cost.
// The state: which candidate is next (i) and how much money is left. teams(i, left) counts the
// teams, the empty one included, that candidates i..n-1 can form within left.
// teams(i, left) = teams(i + 1, left) + teams(i + 1, left - cost[i]) when cost[i] <= left.
// At most n * (budget + 1) states, O(1) work each: O(n * B) time and memory for B = budget.
export function countTeamsMemo(cands: Candidate[], budget: number): number {
const memo = new Map<number, number>();
function teams(i: number, left: number): number {
if (i === cands.length) return 1; // no candidates left: only the empty team
const key = i * (budget + 1) + left; // unique, because 0 <= left <= budget
const known = memo.get(key);
if (known !== undefined) return known;
let result = teams(i + 1, left); // skip candidate i
if (cands[i].cost <= left) result += teams(i + 1, left - cands[i].cost); // take candidate i
memo.set(key, result);
return result;
}
return teams(0, budget) - 1; // the empty team is not a team
}
// The same states in a table, filled from the last candidate up. O(n * B) time and memory.
export function countTeamsTable(cands: Candidate[], budget: number): number {
const n = cands.length;
const table: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(budget + 1).fill(0));
table[n].fill(1); // no candidates left: only the empty team
for (let i = n - 1; i >= 0; i--)
for (let left = 0; left <= budget; left++)
table[i][left] = table[i + 1][left] + (cands[i].cost <= left ? table[i + 1][left - cands[i].cost] : 0);
return table[0][budget] - 1;
}
The same file holds Module 10’s search with a counter, countTeamsSearch, and the next section’s countTeamsRow. It also checks and times all four.
The memo needs one key for two numbers. i * (budget + 1) + left gives every pair its own number, because left is always between 0 and budget. The table version fills table[i] from the last candidate up, because row i reads only row i + 1. Figure 6 is that table for the four candidates, as trace-demo.ts prints it.
i next left: 0 1 2 3 4 5 6 7
4 (none) 1 1 1 1 1 1 1 1
3 Di 4 1 1 1 1 2 2 2 2
2 Cy 5 1 1 1 1 2 3 3 3
1 Bo 2 1 1 2 2 3 4 5 6
0 Ana 3 1 1 2 3 4 6 7 9
teams(0, 7) = 9, minus the empty team = 8
Figure 6: each cell adds the cell below it and, if the candidate fits, the cell cost columns left of that one. So the table fills from the bottom row up.
Module 10 found the same 8 teams for a budget of 700. The table has (n + 1) · (B + 1) cells, each filled in O(1), so countTeamsTable and countTeamsMemo are O(n · B) time and memory. The search does one step per team, so it is O(n log n + T) for T teams, with the n log n for its sort.
node teams-count.ts checks all four against Module 10’s allTeamsBrute on 50 random lists. Then it counts the teams in five random lists of each size and times the four with a budget of 3,000:
teams under 700: 8, 8, 8, 8
same counts as allTeamsBrute on 50 random lists: true
n = 20: teams under 3000 in 5 random lists: 29,713, 52,162, 63,376, 23,757, 96,030
n = 40: teams under 3000 in 5 random lists: 2,278,044, 31,261,583, 1,490,267, 3,330,241, 8,113,842
n = 80: teams under 3000 in 5 random lists: 2,109,501,826, 2,258,057,492, 3,609,630,412, 1,134,265,084, 1,865,031,253
countTeamsSearch, budget 3000
n median ms x prev
20 0.41
30 5.66 13.9
40 40.96 7.2
countTeamsMemo, budget 3000
n median ms x prev
20 1.30
30 4.46 3.4
40 6.15 1.4
countTeamsTable, budget 3000
n median ms x prev
20 0.27
30 0.40 1.5
40 0.92 2.3
countTeamsRow, budget 3000
n median ms x prev
20 0.12
30 0.15 1.3
40 0.20 1.3
countTeamsRow, budget 3000, more candidates
n median ms x prev
40 0.19
80 0.33 1.7
160 0.65 2.0
countTeamsRow, 80 candidates, budget B
n median ms x prev
3,000 0.33
30,000 4.21 12.8
300,000 41.67 9.9
At 40 candidates, the search took 40.96 ms and the one-row table 0.20 ms. The search rows are rough, because the number of teams in a random list of 40 ranged from 1.5 million to 31 million.
At 80 candidates there were 1.1 to 3.6 billion teams. At Module 1’s budget of about 10⁸ simple steps per second, the search would take about 10 to 40 seconds (not run). The one-row table took 0.33 ms, and it doubled with the candidates, from 80 to 160.
The memo was the slowest of the three dynamic programming versions, 6.15 ms at 40. It does the same O(n · B) work as the table, but each state costs a Map lookup, a Map insert and a function call.
The last table shows the price of this state. The work is n · B, so a budget 10 times larger made countTeamsRow about 10 times slower. If the costs were in cents, B would be 100 times larger, and so would the table.
Rule: To find the state, ask what the rest of the problem needs to know about the choices so far. Then the cost is the number of states times the work per state.
Keep only the last row
Row i of the table reads only row i + 1, so you don’t need the other rows. countTeamsRow, an excerpt of teams-count.ts, keeps one array:
// One row instead of the table: row i needs only row i + 1. Go from the largest left down, so
// row[left - cost] still holds row i + 1's value when it is read. O(n * B) time, O(B) memory.
export function countTeamsRow(cands: Candidate[], budget: number): number {
const row = new Array<number>(budget + 1).fill(1);
for (let i = cands.length - 1; i >= 0; i--)
for (let left = budget; left >= cands[i].cost; left--) row[left] += row[left - cands[i].cost];
return row[budget] - 1;
}
row starts as the row below and is updated in place to become row i. But each cell reads a cell to its left, row[left - cost], which the same pass may already have changed.
Pause and predict. The pass for a candidate can go from left = cost up to the budget, or from the budget down to cost. Which direction counts each candidate at most once?
Figure 7 traces the pass for Bo, as trace-demo.ts prints it. The row starts as row 2 of Figure 6 and ends as row 1.
row before: 1 1 1 1 2 3 3 3
left 7: row[7] 3 + row[5] 3 (not updated yet) = 6
left 6: row[6] 3 + row[4] 2 (not updated yet) = 5
left 5: row[5] 3 + row[3] 1 (not updated yet) = 4
left 4: row[4] 2 + row[2] 1 (not updated yet) = 3
left 3: row[3] 1 + row[1] 1 (not updated yet) = 2
left 2: row[2] 1 + row[0] 1 (not updated yet) = 2
row after: 1 1 2 2 3 4 5 6
Figure 7: going from the largest left down, every cell a step reads is to its left and not yet updated, so it still holds the row below.
Going up instead, row[left - cost] would already include Bo when a larger left reads it, so Bo could join a team twice. The common mistakes section shows the wrong count it gives. Going down, countTeamsRow is O(n · B) time and O(B) memory.
The same idea cuts any table whose rows read only the row before. A grid where each cell reads the cells below and to its right needs one row. Two lists compared position by position need two rows. The next section has both.
Keeping one row costs something. You lose the earlier rows, so you can say how many teams there are, but not which candidates make up each one. To rebuild the items of an answer, keep the full table and walk back through it.
Rule: When row i reads only row i + 1, keep one row. Then check which row each cell you read must hold, and fill in the direction that keeps it there.
Three common shapes
Most dynamic programming problems use one of three kinds of state:
- one number that runs up to a target, such as an amount to pay
- an index into each of two lists
- a cell of a grid
variations.ts in the lab writes the first two. Here are fewestCoins and lcsTwoRows, an excerpt. The same file also holds lcsTable, the full-table version that the LCS section below describes.
// Module 9's coin table. fewest[a] = the fewest coins that add up to exactly a.
// fewest[a] = 1 + the smallest fewest[a - c] over the coins c <= a. fewest[0] = 0.
// O(amount * k) time for k coins, O(amount) memory. Returns -1 when no mix of coins adds up to amount.
export function fewestCoins(coins: number[], amount: number): number {
const fewest = new Array<number>(amount + 1).fill(Infinity);
fewest[0] = 0;
for (let a = 1; a <= amount; a++)
for (const c of coins) if (c <= a && fewest[a - c] + 1 < fewest[a]) fewest[a] = fewest[a - c] + 1;
return fewest[amount] === Infinity ? -1 : fewest[amount];
}
// The same length with two rows: row i needs only row i - 1. O(m * n) time, O(n) memory.
export function lcsTwoRows(a: string, b: string): number {
let above = new Array<number>(b.length + 1).fill(0);
let row = new Array<number>(b.length + 1).fill(0);
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++)
row[j] = a[i - 1] === b[j - 1] ? above[j - 1] + 1 : Math.max(above[j], row[j - 1]);
[above, row] = [row, above]; // the row just filled is the next row's "above"
}
return above[b.length];
}
node variations.ts printed:
fewestCoins([1, 3, 4], 6): 2
fewestCoins([1, 5, 10, 25], 63): 6
fewestCoins([4, 6], 7): -1
lcs("deploy", "replay"): 4 4
lcsTable (full table)
n median ms x prev
1,000 13.13
2,000 33.65 2.6
4,000 155.39 4.6
lcsTwoRows
n median ms x prev
1,000 5.09
2,000 19.98 3.9
4,000 80.58 4.0
One answer per amount
Module 9 found that “take the largest coin first” fails for coins of 1, 3 and 4. It pays 6 as 4 + 1 + 1, where 3 + 3 is two coins.
It checked that rule against a table, coinsBest, and fewestCoins is that table. The state is the amount still to pay. However you paid the first part, the fewest coins for what’s left stay the same.
That is the property “best answer” problems need. A problem has optimal substructure when its best answer is made of best answers to its subproblems. So if the best way to pay 6 starts with a 3, the rest must be a best way to pay 3.
Figure 8 fills the table for 6, as trace-demo.ts prints it, with the last coin each amount used.
amount 0 1 2 3 4 5 6
fewest 0 1 2 1 1 2 2
last coin - 1 1 3 4 1 3
6 = 3 + 3
Figure 8: each amount tries every coin as its last coin and keeps the smallest count, and following the last coins back from 6 gives 3 + 3.
fewestCoins is O(amount · k) time for k coins and O(amount) memory. It returns −1 when no mix of coins adds up to the amount, as for 7 with coins of 4 and 6. Each coin can be used any number of times here. The teams count used each candidate at most once, which is why it needed the candidate in its state.
The signs are “the fewest”, “the most” or “how many ways” to reach an exact total, with items you can reuse.
Two lists, one table
The longest common subsequence (LCS) of two lists is the most items that appear in both in the same order, not necessarily next to each other. For example, “deploy” and “replay” share “eply”, so their LCS is 4.
The state is a position in each list: t[i][j] is the LCS of the first i letters of a and the first j letters of b. If the last letters are equal, they end a common subsequence, and t[i][j] = t[i − 1][j − 1] + 1. Otherwise one of them isn’t in it, so t[i][j] is the larger of t[i − 1][j] and t[i][j − 1]. Figure 9 is the table for “deploy” and “replay”, as trace-demo.ts prints it.
r e p l a y
0 0 0 0 0 0 0
d 0 0 0 0 0 0 0
e 0 0 1 1 1 1 1
p 0 0 1 2 2 2 2
l 0 0 1 2 3 3 3
o 0 0 1 2 3 3 3
y 0 0 1 2 3 3 4
Figure 9: a cell adds 1 to its upper-left neighbor when its letters match (e, p, l, y), and otherwise copies the larger of its upper and left neighbors.
lcsTable is O(m · n) time and memory for lists of m and n items. Each row reads only the row above, so lcsTwoRows keeps two rows and swaps them: O(m · n) time and O(n) memory. It was also faster, 80.58 against 155.39 ms at 4,000 letters.
The signs are two strings or lists and “longest common”, “fewest edits” or “what changed between them”.
A grid
The third shape walks a grid where each move goes right or down, such as the cheapest path from the top-left cell to the bottom-right one. The state is a cell (r, c). A path never moves up or left, so each cell reads only cells below it and to its right, and the table fills from the bottom-right corner. The next section uses that problem to compare memo keys.
The sign is a grid with moves in only two directions. If a path can also move up or left, the cells read each other in a circle and no fill order exists. Then the problem is a shortest path, and Module 8‘s Dijkstra’s algorithm fits.
Underneath: dynamic programming in JavaScript
A key for two numbers
A memo for a state of two numbers needs one key per state. keys.ts in the lab compares the choices on the cheapest grid path, solved four ways:
- a
Mapwith the string key`${r},${c}` - a
Mapwith the number keyr * C + c - a bottom-up table
- a bottom-up single row
The two Map versions are the same top-down function as waysMemo, with a different key line. The string version builds const key = `${r},${c}`; and the number version const key = r * C + c;.
node keys.ts checks the four against each other on 20 random grids, then times them on n × n grids:
the four versions agree on 20 random grids: true
string key `${r},${c}`
n median ms x prev
200 13.65
400 72.52 5.3
800 425.96 5.9
number key r * C + c
n median ms x prev
200 6.84
400 27.58 4.0
800 172.87 6.3
bottom-up table
n median ms x prev
200 0.61
400 2.07 3.4
800 8.96 4.3
bottom-up, one row
n median ms x prev
200 0.39
400 1.36 3.5
800 5.21 3.8
All four are O(R · C), and the table rows grew close to 4 times per doubling of the side.
The string key took 425.96 ms at 800 × 800, 2.5 times the number key. Every lookup builds a new string, and the Map has to hash it, which means turning the whole string into a number (Module 3). The table took 8.96 ms, 19 times faster than the number key, because it has no hashing and no function call per state, only an array read.
A top-down memo has one advantage. It stores only the states the recursion reaches, while a table fills every state. When only a small part of the states can be reached, top down can do less work. We didn’t measure a case like that in this module.
How deep the top-down version can go
The memo’s recursion is as deep as the longest chain of subproblems, such as n for the steps or R + C for the grid. waysMemo handled 6,911 steps cold and 9,569 warm before it threw a RangeError. So use a memo when the chain is short or the states are few, and a table when the chain can reach thousands.
Other choices, and when they win
- A greedy rule (Module 9) makes one choice per step and never stores a table. When the rule is safe, as for coins of 1, 5, 10 and 25, it’s cheaper. When it isn’t, as for coins of 1, 3 and 4, dynamic programming gives the right answer.
- Backtracking (Module 10), a search that tries each choice and then undoes it, is still the tool when you need every answer, not their number or the best one. A table of counts can’t list the teams.
- A table over the values costs O(n · B) when B is a budget or an amount. When B is huge and n is small, such as 30 items with costs in the billions, a search over the 2ⁿ subsets can be cheaper.
- Dijkstra’s algorithm (Module 8) replaces the table when moves can go in any direction and no fill order exists.
A shorter memo in ES2026
The method itself hasn’t changed, but JavaScript now makes a memo shorter. Map.prototype.getOrInsertComputed (Module 3) returns the stored value, or runs a callback, stores its result and returns it. It is part of the Upsert proposal, finished for ES2026, as the TC39 finished proposals list shows. It works on Node.js 26.
Here is waysInsert, an excerpt of memo-insert.ts:
// The callback runs only when n is not in the Map, and its result is stored before it's returned.
// The check is "is the key there", not "is the value truthy", so a stored 0 counts as stored.
export function waysInsert(n: number, memo = new Map<number, number>()): number {
if (n <= 1) return 1;
return memo.getOrInsertComputed(n, () => waysInsert(n - 1, memo) + waysInsert(n - 2, memo));
}
node memo-insert.ts checks it against waysMemo for n up to 70 and printed waysInsert(40): 165580141. The callback may call waysInsert again, as it does here.
The method checks whether the key is there, not whether the value is truthy, so a stored 0 counts as stored. That rules out the second mistake below. Its cost is that it needs Node.js 26 or a browser that ships it.
Common mistakes
mistakes.ts writes six bugs that are easy to make in dynamic programming, and prints what each one returns.
Pause and predict. Mistake 2 checks the memo with if (memo.get(k)). It counts the ways to climb 101 steps with moves of 4 or 6, which is 0. How many calls does it make?
node mistakes.ts printed:
1. ways(0) = 0, n = 1..5: [ 1, 1, 2, 3, 5 ] (correct: [1, 2, 3, 5, 8])
2. truthy memo check, n = 101: { ways: 0, calls: 4287295 } fixed: { ways: 0, calls: 101 }
3. key for (1, 11) = "111"
3. key for (11, 1) = "111" collides with (1, 11)
4. new Map in every call, n = 25: 242785 calls; one shared Map: 49 calls
5. table of length n, n = 10: undefined (correct: 89)
6. teams of [Ana 300] under 600, low to high: 2 high to low: 1
A wrong base case. With ways(0) = 0 instead of 1, every answer moves one place: ways(2) came out as 1. Check the base cases by hand on the smallest inputs, n = 0 and n = 1, before anything else.
A truthy check on the memo. if (memo.get(k)) treats a stored 0 as missing. Every odd number of steps has 0 ways, so every one of those states was solved again: 4,287,295 calls instead of 101. Compare with undefined, or use memo.has(k) or getOrInsertComputed.
A key that two states share. `${r}${c}` turns both (1, 11) and (11, 1) into “111”, so the second state reads the first one’s answer. There’s no error, only a wrong result. Put a separator in a string key, `${r},${c}`, or use r * C + c.
A new memo in every call. A Map created inside the recursive function is empty for every call, so nothing is shared. It made 242,785 calls for 25 steps, the same as waysSlow (2 · ways(25) − 1). Create the memo once, outside the recursion, and pass it down.
A table one slot short. new Array(n) has the slots 0 to n − 1, so table[n] is undefined, and adding it to a number gives NaN. A table for the subproblems 0 to n needs n + 1 slots.
One row filled in the wrong direction. With Ana alone, cost 300, and a budget of 600, there is one team. Filling the row from low to high counted 2, because Ana’s update at 600 read row[300], which Ana’s update had already changed. So Ana was counted twice in one team.
When each item can be used once, fill from high to low. When items can be reused, as with coins, low to high is the right order.
Exercises
The exercises are in the module’s exercises folder, each with a test file, and the solutions are in solutions. Run all the tests with:
node --test "exercises/*.test.ts"
All 26 tests fail until you write the four answers. Each exercise ends with a test that a correct but slow answer fails on time. The slow folder holds such answers, with a copy of each test. Some tests compare your answer with a brute force, a slow answer that tries every option.
Exercise 1: the most pay without two shifts in a row (easy)
You can work any of a list of shifts, each with its pay, but never two shifts in a row. Write maxPay(pays): the most you can earn. Start from exercises/max-pay.ts:
// Exercise 1: pays[i] is what shift i pays, and every pay is positive. You can't work two shifts
// in a row. Returns the most you can earn. There can be up to 100,000 shifts.
export function maxPay(pays: number[]): number {
throw new Error("not implemented");
}
For pays of 100, 200, 300 and 100, the answer is 400, from shifts 0 and 2. For 90, 100 and 90, taking the biggest pay first gives 100, but 90 + 90 is 180. The tests also check no shifts, one and two shifts, and 200 random lists against a brute force. Then they check 100,000 shifts, and 38 shifts in under 100 ms.
Hint
Find the state first. After deciding on shifts 0 to i, what does the rest depend on? Write best(i) from best(i − 1) and best(i − 2), then fill it bottom up. Which section said how deep a top-down memo can go?
Solution
// Exercise 1: pays[i] is what shift i pays, and every pay is positive. You can't work two shifts
// in a row. Returns the most you can earn. There can be up to 100,000 shifts.
// State: best(i) = the most from shifts 0..i. Skip shift i, or work it and skip shift i - 1:
// best(i) = max(best(i - 1), best(i - 2) + pays[i]). Bottom up with the last two values, so no
// recursion: O(n) time, O(1) memory.
export function maxPay(pays: number[]): number {
let before = 0; // best(i - 2)
let last = 0; // best(i - 1)
for (const pay of pays) [before, last] = [last, Math.max(last, before + pay)];
return last;
}
Cost: one pass with two variables, so O(n) time and O(1) memory. The recursion without a memo, as slow/max-pay.ts does, solves best(i − 3) from both of its callers and so on down, so it’s O(φⁿ). It took 1,146 ms on the last test. It also throws a RangeError on 100,000 shifts, and so does a top-down memo, because the chain is 100,000 calls deep.
Exercise 2: paths through a grid with blocked cells (easy)
A grid is a list of rows of equal length, with “.” for an open cell and “#” for a blocked one. Write countPaths(grid): how many paths go from the top-left cell to the bottom-right cell, moving only right or down through open cells. Start from exercises/count-paths.ts:
// Exercise 2: grid is a list of rows of equal length, "." for an open cell and "#" for a blocked
// one. Returns how many paths go from the top-left cell to the bottom-right cell, moving only
// right or down through open cells. An empty grid has 0 paths. Counts stay below 2^53.
export function countPaths(grid: string[]): number {
throw new Error("not implemented");
}
An open 3 × 3 grid has 6 paths, and blocking the middle cell leaves 2. The tests also check a blocked start or end, one row, one column, the empty grids [] and [""], and 300 random grids against a brute force. The last test counts the 40,116,600 paths of an open 15 × 15 grid in under 100 ms.
Hint
The state is a cell. A path reaches (r, c) from the cell above or the cell to its left, and a blocked cell has 0 paths. “Keep only the last row” and the grid in “Three common shapes” show how one row is enough. Which row must the cell to the left hold?
Solution
// Exercise 2: grid is a list of rows of equal length, "." for an open cell and "#" for a blocked
// one. Returns how many paths go from the top-left cell to the bottom-right cell, moving only
// right or down through open cells. An empty grid has 0 paths. Counts stay below 2^53.
// State: paths(r, c) = paths(r - 1, c) + paths(r, c - 1), and 0 for a blocked cell.
// One row: before row[c] is overwritten, it holds the count for the cell above.
// O(R * C) time, O(C) memory.
export function countPaths(grid: string[]): number {
if (grid.length === 0 || grid[0].length === 0) return 0;
const cols = grid[0].length;
const row = new Array<number>(cols).fill(0);
row[0] = 1; // one way to stand on the start cell, if it's open
for (let r = 0; r < grid.length; r++)
for (let c = 0; c < cols; c++) {
if (grid[r][c] === "#") row[c] = 0;
else if (c > 0) row[c] += row[c - 1]; // from above (the old row[c]) plus from the left
}
return row[cols - 1];
}
Cost: each cell is filled once from two neighbors, so O(R · C) time. One row of C counts is O(C) memory. Here the row goes left to right. The cell to the left must already hold this row’s count, and the cell above is the old value of row[c].
The recursion without a memo, as slow/count-paths.ts does, walks every path one cell at a time. On the open 15 × 15 grid that’s 40 million paths, and it took 1,965 ms.
Exercise 3: fewest edits with little memory (medium)
The edit distance (or Levenshtein distance) between two strings is the fewest single-character insertions, deletions and replacements that turn one into the other. That is the definition in the NIST Dictionary of Algorithms and Data Structures. Write editDistance(a, b), using memory that grows with the shorter string. Start from exercises/edit-distance.ts:
// Exercise 3: returns the fewest single-character edits (insert a character, delete one, or
// replace one with another) that turn a into b. Use memory that grows with the shorter string,
// not with a.length * b.length.
export function editDistance(a: string, b: string): number {
throw new Error("not implemented");
}
“colour” to “color” is 1 edit, “sunday” to “saturday” is 3, and “deploy” to “replay” is 2. The tests also check empty strings, both directions, 200 random pairs against a brute force, and a 200,000-letter string against a 2-letter one. Then they run 1,000,000 letters against 30 in under 1,000 ms, and two 12-letter strings in under 100 ms. The tests can’t check the memory, but the 1,000,000-letter test fails a full table on time.
Hint
Use the LCS table’s state: d[i][j] for the first i letters of a and the first j letters of b. The last step either deleted a’s last letter, inserted b’s last letter, or kept or replaced it. What are row 0 and column 0? Then keep two rows, as lcsTwoRows does, and make them as long as the shorter string.
Solution
// Exercise 3: returns the fewest single-character edits (insert a character, delete one, or
// replace one with another) that turn a into b. Use memory that grows with the shorter string,
// not with a.length * b.length.
// State: d(i, j) = the edits that turn a[0..i) into b[0..j). The last step deleted a[i - 1],
// inserted b[j - 1], or kept or replaced a[i - 1] with b[j - 1]:
// d(i, j) = min(d(i - 1, j) + 1, d(i, j - 1) + 1, d(i - 1, j - 1) + (a[i - 1] === b[j - 1] ? 0 : 1)).
// d(0, j) = j inserts, d(i, 0) = i deletes. Two rows, each as long as the shorter string.
// O(m * n) time, O(min(m, n)) memory.
export function editDistance(a: string, b: string): number {
if (b.length > a.length) [a, b] = [b, a]; // the distance is the same both ways; make b the shorter
let above = Array.from({ length: b.length + 1 }, (_, j) => j); // row 0: j inserts
let row = new Array<number>(b.length + 1);
for (let i = 1; i <= a.length; i++) {
row[0] = i; // i deletes
for (let j = 1; j <= b.length; j++)
row[j] = Math.min(above[j] + 1, row[j - 1] + 1, above[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
[above, row] = [row, above];
}
return above[b.length];
}
Cost: (m + 1) · (n + 1) cells, each O(1), so O(m · n) time. Two rows as long as the shorter string are O(min(m, n)) memory. The distance is the same in both directions, because each edit has an opposite edit (insert and delete, replace and replace back), so swapping the strings is safe.
The recursion without a memo, as slow/edit-distance.ts does, makes three calls per call and took 2,342 ms on the two 12-letter strings. A full table, as slow/edit-distance-table.ts does, builds a million arrays for the 1,000,000-letter string. It took 2,212 ms on that test when copied over the slow answer.
Exercise 4: the most valuable bookings for one room (harder)
A room takes bookings, each with a start, an end and a value, and two bookings can’t overlap. Write mostValue(bookings): the largest total value of bookings that fit together. Start from exercises/most-value.ts:
// Exercise 4: each booking is [start, end, value] for one room, half-open [start, end) with
// end > start, so a booking that ends at 10 and one that starts at 10 fit together. Returns the
// largest total value of bookings that don't overlap. You may import Module 9's bounds:
// import { lowerBound, upperBound } from "../../module-09/bounds.ts";
export type Booking = [start: number, end: number, value: number];
export function mostValue(bookings: Booking[]): number {
throw new Error("not implemented");
}
Module 9’s rule, the earliest end first, takes the most bookings, but not the most value. For [9, 10] worth 10, [9, 12] worth 100 and [10, 11] worth 10, it takes the two worth 10 and misses 100. The tests also check bookings that touch, no bookings, an input left in its order, and 300 random days against a brute force. The last test has 40,000 bookings, in under 100 ms.
Hint
Sort the bookings by end. Then take or skip the last one, as the teams count took or skipped a candidate. If you take it, which earlier bookings can still be taken, and how does Module 9’s upperBound on the sorted ends find them?
Solution
// Exercise 4: each booking is [start, end, value] for one room, half-open [start, end) with
// end > start, so a booking that ends at 10 and one that starts at 10 fit together. Returns the
// largest total value of bookings that don't overlap. You may import Module 9's bounds:
// import { lowerBound, upperBound } from "../../module-09/bounds.ts";
import { upperBound } from "../../module-09/bounds.ts";
export type Booking = [start: number, end: number, value: number];
// Sort by end. State: best[i] = the most value from the first i bookings in that order.
// Skip booking i - 1, or take it plus the best of the bookings that end by its start:
// best[i] = max(best[i - 1], best[p] + value), where p = upperBound(ends, start) counts the
// bookings that end at or before the start (all of them come before i - 1, because end > start).
// O(n log n) time for the sort and n binary searches, O(n) memory.
export function mostValue(bookings: Booking[]): number {
const byEnd = bookings.toSorted((x, y) => x[1] - y[1]);
const ends = byEnd.map((b) => b[1]);
const best = new Array<number>(byEnd.length + 1).fill(0);
for (let i = 1; i <= byEnd.length; i++) {
const [start, , value] = byEnd[i - 1];
best[i] = Math.max(best[i - 1], best[upperBound(ends, start)] + value);
}
return best[byEnd.length];
}
Cost: the sort is O(n log n), and each of the n states does one binary search, O(log n). So it’s O(n log n) time and O(n) memory for the sorted copy, the ends and the table. upperBound(ends, start) counts the bookings that end at or before the start. Because every booking ends after it starts, they all come before the current one.
The same table with a scan back for that count, as slow/most-value.ts does, is O(n²) when many bookings overlap. It took 1,505 ms on the last test.
Going deeper
You can skip this section. It covers details the main path left out.
Why the slow calls are 2 · ways(n) − 1
The calls for n are one plus the calls for n − 1 and n − 2. So the calls plus one follow the same rule as the counts. They start at 2 and 2, twice the counts’ 1 and 1, so they stay twice the count. The counts themselves are the Fibonacci numbers, shifted by one place.
Cold and warm stack limits
“Cold” calls waysMemo once in a new process, and “warm” first runs it 2,000 times. By then V8, the JavaScript engine inside Node.js, has compiled it. Its JIT compiler turns functions that run often into machine code while the program runs. A compiled function uses smaller stack frames, so more of them fit, as Module 6 measured.
What the 80 MB table costs
A research script, table-growth.ts, forced a garbage collection before each call of waysTable. It found under 1.1 ms of garbage collection inside a call. But the 1,000,000 row took about 14.6 ms there instead of 3.41. So these rows measure getting fresh memory as much as the additions, and we didn’t find the exact cause.
Why the Map versions grew faster than 4 times
Both Map versions in keys.ts grew 5.3 to 6.3 times per doubling at the larger sizes. A growing Map rehashes into a bigger table (Module 3), and the garbage collector has to trace it. We didn’t measure which of the two costs more here.
What a table holds
memory.ts measures the heap that lcsTable holds for two strings of n letters. It runs each size in a fresh process and forces a garbage collection before each reading. Run it with node --expose-gc memory.ts:
n = 1,000: the full table holds 7.7 MB, 8.06 bytes per cell; two rows hold 2002 numbers (same answer: true)
n = 2,000: the full table holds 30.7 MB, 8.03 bytes per cell; two rows hold 4002 numbers (same answer: true)
n = 4,000: the full table holds 122.4 MB, 8.01 bytes per cell; two rows hold 8002 numbers (same answer: true)
Each cell costs 8 bytes, one array slot on Node.js 26 on x64, which is built without pointer compression. So a full 4,000 × 4,000 table holds 122.4 MB, and two rows hold 8,002 numbers, about 64 KB.
That memory also shows in the time. The full LCS table grew 2.6 and 4.6 times per doubling, against 4, while the two rows grew 3.9 and 4.0. A first version of memory.ts measured all three sizes in one loop and got 91.7 MB at 4,000. The previous size’s table was still alive when the next “before” was read.
When the counts outgrow a Number
Counting problems grow fast, and Module 9 showed that a Number holds integers exactly only up to 2⁵³ − 1, Number.MAX_SAFE_INTEGER. A BigInt is a JavaScript integer with no size limit, written with an n suffix such as 1n. precision.ts checks where the count of ways passes 2⁵³ − 1, with a BigInt copy of waysTwoVars called waysBig.
Pause and predict. waysTwoVars(78) returns a Number. Is it right?
node precision.ts printed:
Number.MAX_SAFE_INTEGER = 9007199254740991 = 2^53 - 1: true
ways(77) = 8944394323791464 safe: true
ways(78) = 14472334024676221 safe: false
first n over MAX_SAFE_INTEGER: 78; first n where the Number answer is wrong: 78
ways(78): Number 14472334024676220, exact 14472334024676221
ways(100): Number 573147844013817200000, exact 573147844013817084101
Number.isSafeInteger(waysTwoVars(78)): false
waysTwoVars(1475) = 1.3069892237633987e+308; waysTwoVars(1476) = Infinity
waysBig(10) + 1 -> TypeError: Cannot mix BigInt and other types, use explicit conversions
waysBig(10) + 1n -> 90n
At 78 steps the Number version is off by 1, with no error. At 100 steps it’s off by about 116,000. The opening’s 60 steps, 2,504,730,781,961 ways, is still exact.
Number.isSafeInteger tells you when a result has left the safe range. A BigInt keeps it exact, but BigInt and Number can’t be mixed in one expression. So you write 1n, not 1, or get a TypeError. Each BigInt addition is also slower than a Number addition, though we didn’t measure by how much.
Where the name comes from
Richard Bellman chose the name in the fall of 1950 at RAND, as his autobiography (1984) tells. Stuart Dreyfus published that excerpt in Operations Research (2002). Bellman wrote that the Secretary of Defense, Wilson, hated the word “research”, so he wanted a name that hid the mathematics.
He passed over “planning” and took “programming”. He chose “dynamic” because the processes had many stages and changed over time. He also liked that, in his words, “it’s impossible to use the word, dynamic, in a pejorative sense”.
Cheat sheet
Figure 10 is the summary of the module: which state fits which sign in a problem.
sign in the problem state table cost
"ways to climb", one step at a time n 1D O(n)
take or skip each item, a budget (item, left) 2D -> row O(n * B)
reach an exact total, reuse items amount left 1D O(amount * k)
two strings or lists (i, j) 2D -> 2 O(m * n)
grid, moves right or down only (r, c) 2D -> row O(R * C)
every answer, not how many (no table) backtrack 2^n (Module 10)
Figure 10: dynamic programming pays once per state, so the state you choose sets both the time and the memory.
- Spot it: a recursion that calls itself more than once, with far fewer different arguments than calls; “how many ways”, “the fewest”, “the longest”.
- State: what the rest of the problem needs to know about the choices so far. Cost = states × work per state.
- Top down: the recursion plus a
Mapcreated once; compare withundefined. Depth is the longest chain (about 7,000 to 9,500 frames here). - Bottom up: fill from the smallest subproblem; keep only the rows later cells read. Fill high to low when each item is used once.
- Numbers: counts pass 2⁵³ − 1 quickly; check
Number.isSafeIntegeror use BigInt. - Next: Module 12 puts the patterns of the course side by side and teaches a method to choose between them.
Sources
- Stuart Dreyfus, “Richard Bellman on the Birth of Dynamic Programming”, Operations Research 50(1):48–51, 2002 (excerpts from Bellman’s Eye of the Hurricane, 1984), PDF copy.
- NIST Dictionary of Algorithms and Data Structures, Levenshtein distance, modified May 15, 2019.
- ECMAScript,
Number.MAX_SAFE_INTEGER. - V8 blog, BigInt: arbitrary-precision integers in JavaScript, Mathias Bynens (May 1, 2018).
- TC39 finished proposals (Upsert, 2026), read November 2026.