LeetCode Collections: Interview Problems from Naive to Optimal / Module 11

Module 11: Dynamic Programming

Work eight dynamic programming problems as spoken interviews, from Coin Change by plain recursion to a table, and say when a memo overflows the stack.

Here is a first answer to 322. Coin Change: to pay an amount with the fewest coins, try each coin as the last one, and pay what’s left the same way.

// Time O(k^(amount / smallest coin)), k = number of coins: every call tries every coin again,
// and the same remainder is solved again and again. Memory O(amount / smallest coin): the call stack.
export function coinChangeRecursive(coins: number[], amount: number): number {
  function fewest(remaining: number): number {
    if (remaining === 0) return 0;
    let best = Infinity;
    for (const coin of coins) {
      if (coin <= remaining) best = Math.min(best, 1 + fewest(remaining - coin));
    }
    return best;
  }
  const answer = fewest(amount);
  return answer === Infinity ? -1 : answer;
}

It’s correct, and LeetCode allows amounts up to 10⁴. With the coins [1, 2, 5], it took 625.40 ms at amount 34 in the measurement at the end of this page. At amount 100 it would make about 2.2 × 10²³ calls. A table of the 35 answers for amounts 0 to 34 took 0.01 ms.

This module works eight problems where the same smaller question comes up again and again. Each one follows the nine steps from Module 1, and each goes through the same four solutions: plain recursion, a memo, a table, and a table with fewer rows.

After this module, you can:

  • write a problem’s answer as a recurrence, code it as plain recursion, and name the work it repeats
  • save each answer in a memo, then turn the memo into a table filled from the smallest case up
  • keep only the cells the next cell needs, and say when that isn’t possible
  • say when a memo’s chain of calls is too deep for Node.js’s call stack, and switch to the table
  • find the longest increasing subsequence in O(n log n) with patience sorting

The code for this module is in module-11/ of the course repository, and node --test "module-11/**/*.test.ts" from its root runs every test. atlimit.ts in the module folder calls each solution once on a hard input at its problem’s limit, so its times are rough, and yours will differ. Every number on this page comes from Node.js 24.22.1 on an Apple M2 laptop with macOS.

The pattern: solve each smaller question once

A subproblem is the same question on a smaller input: the fewest coins for 3 instead of 6. A formula that gives an answer from the answers to smaller subproblems is a recurrence. Coin Change’s recurrence is fewest(a) = 1 + the smallest fewest(a − c) over the coins c, with fewest(0) = 0.

Plain recursion is the recurrence written as a function. It’s slow when the problem has overlapping subproblems: the same subproblem is reached by many paths, and each time it’s solved from scratch. Dynamic programming solves each subproblem once and saves the answer. DSA Module 11 teaches it from the start, on the same staircase as problem 70.

There are two ways to save the answers. Memoization keeps the recursive function and adds an array, the memo: the function returns a saved answer if there is one, and saves each new answer before it returns. That’s called top down, because it starts from the question asked.

A table fills the same answers bottom up, from the smallest subproblem, in an order where every answer a cell needs is already there. Figure 1 shows the four solutions each problem in this module goes through.

step               what changes                time           catch
1 plain recursion  the recurrence as code      exponential    too slow
2 memo             + an array of answers       states x work  stack depth
3 table            a loop, smallest first      states x work  a cell per state
4 fewer rows       keep only cells still read  states x work  recent cells only

Figure 1: the memo and the table do the same work; the table removes the call stack, and fewer rows save memory when each cell reads only recent cells.

The state is the set of values that decides a subproblem’s answer: the amount left in Coin Change, two positions in two strings in problem 1143. The number of states times the work per state is the cost of steps 2 to 4.

Signs that point to dynamic programming:

  • “the fewest”, “the most”, “the longest”, “how many ways”, or “is it possible”
  • each choice leaves a smaller version of the same question
  • a plain recursion that reaches the same arguments by different paths
  • limits too large for every path (n up to 10⁴), but small enough for every state (10⁶ cells)

The cost is memory: one saved answer per state. And a memo’s recursion is as deep as its longest chain of subproblems. Module 4 explains the call stack: one frame per call that hasn’t returned, in a space whose size V8 caps. A chain of thousands of calls can be more than it holds.

Rule: Write the recurrence, find the state, and solve each state once. Use a table when the chain of states can reach thousands, and keep only the rows the next cell reads.

70. Climbing Stairs

70. Climbing Stairs is rated Easy. A staircase has n steps, and each move climbs one step or two. Count the different sequences of moves that end exactly on the top step.

  • 1 ≤ n ≤ 45

The signature is function climbStairs(n: number): number. Try it on LeetCode first.

Hint

Look at the last move. It climbed one step or two. How many ways reach the step it started from?

Interviewer: Count the ways to climb n steps, one or two at a time.

Candidate: Do different orders count as different ways? Say 1 then 2, and 2 then 1, for three steps.

Interviewer: Yes, those are two ways.

Candidate: Can n be 0? And how large can the answer get?

Interviewer: n is between 1 and 45.

The interviewer and the candidate are invented. The problems, limits and timings are real.

Candidate: Then I’ll check the size of the answer once I have the formula. Here’s my example and two edge cases.

n      expected
5      8              11111, four orders of 2111, three orders of 221
1      1              one move
2      2              11 or 2
45     1,836,311,903  the limit

Candidate: The last move is one step or two. So the ways to reach step n are the ways to reach n − 1 plus the ways to reach n − 2. Standing still at the bottom counts as one way, so ways(0) = 1, and ways(1) = 1.

// Time O(phi^n), phi ~ 1.618: each call makes two more, and the same n is solved again and again.
// Memory O(n): the call stack is n deep.
export function climbStairsRecursive(n: number): number {
  if (n <= 1) return 1;
  return climbStairsRecursive(n - 1) + climbStairsRecursive(n - 2);
}

Pause and predict. How many calls does climbStairsRecursive(5) make?

Figure 2 lists them, one line per call, indented under the call that made it. Each line shows the call’s n.

5
  4
    3
      2
        1
        0
      1
    2           again
      1
      0
  3             again: the whole subtree under the first 3
    2           again
      1
      0
    1

Figure 2: 15 calls for an answer of 8; n = 3 is solved twice and n = 2 three times, and each repeat redoes everything below it.

Candidate: Every call ends in a 0 or a 1, and those leaves add up to the answer. So the calls grow with the answer, about 1.618 times per extra step. At n = 45 the answer is 1.8 × 10⁹, so it’s about 3.7 × 10⁹ calls.

In atlimit.ts, climbStairsRecursive(45) took 8,299.1 ms. That’s too slow for one answer.

Interviewer: What does it repeat?

Candidate: climbStairsRecursive(3) doesn’t depend on who asks for it. Once I know it, I can save it. There are only n + 1 different questions, ways(0) to ways(n), so I keep an array of n + 1 answers, with −1 for “not solved yet”.

// Time O(n): each n from 2 up is computed once. Memory O(n): the memo plus a call stack n deep.
export function climbStairsMemo(n: number): number {
  const memo: number[] = new Array(n + 1).fill(-1);
  function ways(steps: number): number {
    if (steps <= 1) return 1;
    if (memo[steps] !== -1) return memo[steps];
    memo[steps] = ways(steps - 1) + ways(steps - 2);
    return memo[steps];
  }
  return ways(n);
}

Candidate: Now each of the n + 1 states is solved once, with O(1) work, so it’s O(n) time. The memory is the memo plus a chain of up to n calls on the stack, 45 at most.

Candidate: I can also drop the recursion. ways(steps) needs only smaller steps, so I fill the array from 0 upward.

// Time O(n): one pass up the table. Memory O(n): the table.
export function climbStairsTable(n: number): number {
  const ways: number[] = new Array(n + 1).fill(0);
  ways[0] = 1;
  ways[1] = 1;
  for (let steps = 2; steps <= n; steps++) ways[steps] = ways[steps - 1] + ways[steps - 2];
  return ways[n];
}

Interviewer: Can you use less memory?

Candidate: Each cell reads only the two cells below it. So I keep two numbers and move them up one step at a time.

// Time O(n): one pass. Memory O(1): each value needs only the two before it.
function climbStairs(n: number): number {
  let twoBelow = 1; // ways(0)
  let oneBelow = 1; // ways(1)
  for (let steps = 2; steps <= n; steps++) {
    const current = oneBelow + twoBelow;
    twoBelow = oneBelow;
    oneBelow = current;
  }
  return oneBelow;
}

export { climbStairs };

Interviewer: Trace it for 5.

Figure 3 shows the two numbers after each pass of the loop.

steps   current = oneBelow + twoBelow   twoBelow   oneBelow
start                                   1          1
2       1 + 1 = 2                       1          2
3       2 + 1 = 3                       2          3
4       3 + 2 = 5                       3          5
5       5 + 3 = 8                       5          8     returned

Figure 3: each row reads only the row above it, so two numbers hold everything the next step needs.

Candidate: For n = 1 the loop doesn’t run, and oneBelow is 1. For n = 2 it runs once and returns 2.

Interviewer: Final cost?

Candidate: O(n) time, one pass. O(1) memory, two numbers. At 45, the answer is 1,836,311,903, far below 2⁵³, so a Number holds it exactly.

In atlimit.ts, climbStairsMemo(45), climbStairsTable(45) and climbStairs(45) each took under 0.1 ms.

Interviewer: What if each move could climb 1 to k steps?

The Candidate’s answer

Candidate: Then ways(n) is the sum of the k cells below it, O(n · k) with the table. If I keep a running sum of the last k cells, adding the new one and dropping the oldest, it’s O(n).

This version isn’t in the lab.

Interviewer: What if n could be 100?

The Candidate’s answer

Candidate: The answers grow past 2⁵³ − 1, the largest integer a Number holds exactly. ways(78) is the first one over it, and the Number result there is off by one with no error. So I’d use BigInt, with 1n as both starting values.

This version isn’t in the lab.

Two mistakes are common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module that has one.

  • ways(0) = 0. For n = 1 to 5 it returns [1,1,2,3,5] instead of [1,2,3,5,8]: every answer slides one place. Standing still is one way, so ways(0) = 1.
  • A memo created inside the recursive function. Each call gets a new empty memo, so nothing is shared and the cost stays exponential. DSA Module 11 counted 242,785 calls at n = 25 instead of 49. Create the memo once, outside the function that recurses.

Lab folder: module-11/0070-climbing-stairs/ in the course repository.

198. House Robber

198. House Robber is rated Medium. A row of houses each holds an amount, never negative. Pick houses so that no two picked houses are next to each other, and return the largest total.

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 400

The signature is function rob(nums: number[]): number. Try it on LeetCode first.

Hint

For the last house, there are two choices: take it, or skip it. What does each choice leave?

Interviewer: Pick houses, never two side by side, for the largest total.

Candidate: Is the street a line, so the first and last houses aren’t neighbors? And can it be empty?

Interviewer: A line, with at least one house.

Candidate: Amounts are 0 to 400, so the total is at most 50 × 400 = 20,000. Here are my cases.

nums            expected
[5, 1, 1, 5]    10        the two ends
[4]             4         one house
[0, 0, 0]       0
[2, 1, 1, 2]    4         neither all even nor all odd positions

Candidate: For house i, I either skip it and keep the best up to i − 1, or take it and add the best up to i − 2. Every valid pick does one of the two.

// Time O(phi^n): each call makes two more, like Climbing Stairs. Memory O(n): the call stack.
export function robRecursive(nums: number[]): number {
  function best(i: number): number {
    if (i < 0) return 0;
    return Math.max(best(i - 1), best(i - 2) + nums[i]);
  }
  return best(nums.length - 1);
}

Candidate: It has the same shape as Climbing Stairs: two calls, one and two houses back. So it’s O(φⁿ) with φ ≈ 1.618, and at 100 houses that’s about 8 × 10²⁰ calls. It never finishes.

Interviewer: Then fix it.

Candidate: best(i − 2) is solved inside best(i − 1) and again directly. The state is one index, so the memo is one array, with −1 for “not solved” because no total is negative.

// Time O(n): each house is solved once. Memory O(n): the memo plus a call stack n deep.
export function robMemo(nums: number[]): number {
  const memo: number[] = new Array(nums.length).fill(-1);
  function best(i: number): number {
    if (i < 0) return 0;
    if (memo[i] !== -1) return memo[i];
    memo[i] = Math.max(best(i - 1), best(i - 2) + nums[i]);
    return memo[i];
  }
  return best(nums.length - 1);
}

Candidate: The table counts houses instead of indexes, so best[0] is “no houses” and needs no special case.

// Time O(n): one pass. Memory O(n): best[k] is the answer for the first k houses.
export function robTable(nums: number[]): number {
  const best: number[] = new Array(nums.length + 1).fill(0);
  best[1] = nums[0];
  for (let k = 2; k <= nums.length; k++) best[k] = Math.max(best[k - 1], best[k - 2] + nums[k - 1]);
  return best[nums.length];
}

Candidate: And each cell reads the two before it, so two numbers are enough.

// Time O(n): one pass. Memory O(1): each answer needs only the two before it.
function rob(nums: number[]): number {
  let twoBack = 0; // best without the last two houses
  let oneBack = 0; // best without the last house
  for (const value of nums) {
    const current = Math.max(oneBack, twoBack + value);
    twoBack = oneBack;
    oneBack = current;
  }
  return oneBack;
}

export { rob };

Interviewer: Trace [5, 1, 1, 5].

Figure 4 shows each house’s choice: skip it and keep oneBack, or take it and add it to twoBack.

value   skip: oneBack   take: twoBack + value   current   twoBack   oneBack
start                                                     0         0
5       0               0 + 5 = 5               5         0         5
1       5               0 + 1 = 1               5         5         5
1       5               5 + 1 = 6               6         5         6
5       6               5 + 5 = 10              10        6         10

Figure 4: the last house is taken because 5 + 5 beats 6, so the answer, 10, uses both ends.

Candidate: For [2, 1, 1, 2] the same steps give 2, 2, 3, 4: houses 0 and 3, one even position and one odd.

Interviewer: Final cost?

Candidate: O(n) time, one pass. O(1) memory, two numbers. In atlimit.ts, rob took under 0.1 ms on 100 houses.

Interviewer: What if the houses stand in a circle?

The Candidate’s answer

Candidate: Then the first and last are neighbors, so at most one of them is taken. I’d run the line version twice, once without the first house and once without the last, and return the larger. Still O(n) time and O(1) memory.

That’s LeetCode’s 213. House Robber II, which this course doesn’t cover. This version isn’t in the lab.

Interviewer: Can you return which houses to pick?

The Candidate’s answer

Candidate: I’d keep robTable‘s full array and walk it back from the end. House k − 1 was taken if best[k] differs from best[k − 1], and then I jump two back. That needs the O(n) table, not two numbers.

This version isn’t in the lab.

Two mistakes are common here.

  • The better of the even and the odd positions. For [2, 1, 1, 2] it returns 3 instead of 4. The best pick can skip two houses in a row. Use the recurrence.
  • A memo checked with if (memo[i]). A saved 0 reads as “not solved”, so streets of zeros are solved again and again, and the cost goes back toward exponential. DSA Module 11 measured the same bug at 4,287,295 calls instead of 101. Compare with the marker: memo[i] !== -1.

Lab folder: module-11/0198-house-robber/ in the course repository.

322. Coin Change

322. Coin Change is rated Medium. You get coin values, with as many of each coin as you like, and a target amount. Return the fewest coins that add up exactly to the amount, or −1 if no mix of coins does.

  • 1 ≤ coins.length ≤ 12
  • 1 ≤ coins[i] ≤ 2³¹ − 1
  • 0 ≤ amount ≤ 10⁴

The signature is function coinChange(coins: number[], amount: number): number. Try it on LeetCode first.

Hint

The last coin of a best mix is one of the k values. What must the rest of the mix be?

Interviewer: Pay the amount with the fewest coins.

Candidate: Can I use each value as often as I like? And what do I return when the amount can’t be made, or is 0?

Interviewer: Yes, any number of each. Return −1 if it can’t be made, and 0 for amount 0.

Candidate: Is the coin set something like 1, 5, 10, 25, where taking the largest coin first works?

Interviewer: No promise about the values.

Candidate: Then the largest coin first isn’t safe. My example shows why.

coins, amount           expected
[1, 3, 4], 6            2      3 + 3; largest first gives 4 + 1 + 1
[2], 3                  -1     odd amount, even coins
[1], 0                  0      no coins
[2147483647], 2         -1     a coin larger than the amount
[7, 11], 10000          912    904 elevens and 8 sevens, at the limit

Candidate: The first answer is the recursion at the top of this page, coinChangeRecursive. The last coin of a best mix is some coin c, and the rest must be a best mix for amount − c. So I try every coin as the last one and keep the smallest.

Candidate: A remainder with no fitting coin returns Infinity, and the end turns Infinity into −1.

Candidate: Each call tries up to k coins, and with a coin of 1 the chain is amount calls long. So it’s O(k^(amount / smallest coin)) time. At amount 10⁴ it never finishes.

Interviewer: What does it repeat?

Candidate: The same remainder is reached by many orders of the same coins: 1 then 3, and 3 then 1, both leave amount − 4. Its answer doesn’t depend on the order. The state is one number, the remainder, so a memo of amount + 1 cells covers it.

// Time O(amount * k): each remainder is solved once, trying k coins. Memory O(amount): the memo,
// and a call stack up to amount deep (with a coin of 1). See stack-depth.ts: 10^4 deep does not fit.
export function coinChangeMemo(coins: number[], amount: number): number {
  const memo: (number | undefined)[] = new Array(amount + 1); // undefined: not solved yet
  function fewest(remaining: number): number {
    if (remaining === 0) return 0;
    const saved = memo[remaining];
    if (saved !== undefined) return saved; // Infinity ("cannot be made") is a saved answer too
    let best = Infinity;
    for (const coin of coins) {
      if (coin <= remaining) best = Math.min(best, 1 + fewest(remaining - coin));
    }
    memo[remaining] = best;
    return best;
  }
  const answer = fewest(amount);
  return answer === Infinity ? -1 : answer;
}

Candidate: Each of the amount + 1 remainders is solved once, with k coins tried. So it’s O(amount × k), at most 1.2 × 10⁵ steps. The marker for “not solved” is undefined, because Infinity is a real answer: “this remainder can’t be made”.

The lab names this function coinChangeMemo. The version to paste into LeetCode is coinChange, in the answer to the first follow-up below.

Interviewer: Trace your example.

Figure 5 shows the memo for coins [1, 3, 4] and amount 6. With the coin 1 tried first, the first chain of calls goes straight down to 0, so the remainders are saved in the order 1, 2, 3 and up.

remaining   1 + fewest(remaining - c), for c = 1, 3, 4   saved
1           1 + 0 = 1                                     1
2           1 + 1 = 2                                     2
3           1 + 2 = 3,  1 + 0 = 1                         1
4           1 + 1 = 2,  1 + 1 = 2,  1 + 0 = 1             1
5           1 + 1 = 2,  1 + 2 = 3,  1 + 1 = 2             2
6           1 + 2 = 3,  1 + 1 = 2,  1 + 2 = 3             2  returned

Figure 5: fewest(6) = 2 comes from the coin 3 and fewest(3) = 1, and every remainder below 6 is solved once.

Candidate: For [2] and 3, fewest(3) tries 2 and gets 1 + fewest(1). fewest(1) has no coin that fits, so it saves Infinity, and the answer is −1.

Interviewer: Final cost?

Candidate: O(amount × k) time. O(amount) memory for the memo, plus a stack as deep as the longest chain, amount / smallest coin.

Interviewer: LeetCode allows amount 10⁴ with a coin of 1. What happens then?

The Candidate’s answer

Candidate: Then the first chain is fewest(10000), fewest(9999), and so on down to 0: 10⁴ calls waiting at once. That’s more than Node.js’s call stack holds, so I’d fill the same cells in a loop instead. Cell total reads cells below it, so I go from 1 up to the amount.

// Time O(amount * k): amount + 1 cells, k coins each. Memory O(amount): the table.
// No smaller version: a cell can need any earlier cell (a - c for a large coin c), so every row stays.
function coinChange(coins: number[], amount: number): number {
  const fewest: number[] = new Array(amount + 1).fill(Infinity);
  fewest[0] = 0;
  for (let total = 1; total <= amount; total++) {
    for (const coin of coins) {
      if (coin <= total) fewest[total] = Math.min(fewest[total], fewest[total - coin] + 1);
    }
  }
  return fewest[amount] === Infinity ? -1 : fewest[amount];
}

export { coinChange };

Candidate: Same O(amount × k) time and O(amount) memory, and no recursion. I can’t keep fewer cells here: a coin of 5,000 makes cell 10,000 read cell 5,000, so the whole array stays.

In atlimit.ts, coinChangeMemo([1], 10000) threw RangeError: Maximum call stack size exceeded, and coinChange([1], 10000) returned 10000 in 1.0 ms. In the run of stack-depth.ts in the module folder, coinChangeMemo handled a chain of 4,433 calls on a first call, and it failed at 10⁴ after a warm-up too. We don’t know whether LeetCode’s judge runs with a larger stack, so don’t count on it.

Interviewer: What if I ask for the number of ways to pay, instead of the fewest coins?

The Candidate’s answer

Candidate: Then a cell sums instead of taking the minimum. But I’d put the coin loop outside the amount loop, so each mix is counted once, not once per order. Still O(amount × k).

That’s LeetCode’s 518. Coin Change II, which this course doesn’t cover. This version isn’t in the lab.

Interviewer: Could you use a breadth-first search?

The Candidate’s answer

Candidate: Yes. Each amount from 0 up is a node, and a coin is an edge from a to a + c. BFS from 0, as in Module 9, reaches each amount first by the fewest edges, so the level where it reaches the target is the answer.

Candidate: It’s the same O(amount × k) in the worst case, and it can stop early.

This version isn’t in the lab.

Three mistakes are common here.

  • The largest coin first. For [1, 3, 4] and 6 it returns 3 instead of 2. For [2, 5] and 6 it returns −1 instead of 3 (2 + 2 + 2). Try every coin as the last one.
  • Returning the table cell as it is. For [2] and 3 it returns Infinity instead of −1. Turn Infinity into −1 at the end.
  • −1 for both “not solved yet” and “can’t be made”. The answer stays right, but an impossible remainder is solved again on every visit. With coins [2, 4] and odd amounts, which are all impossible, the memo made 232 calls at 21, 28,656 at 41 and 3,524,577 at 61. With a separate marker it made 20, 40 and 60. Use undefined for “not solved”.

Lab folder: module-11/0322-coin-change/ in the course repository.

300. Longest Increasing Subsequence

300. Longest Increasing Subsequence is rated Medium. A subsequence is what’s left of a list after you drop some items, with the rest kept in their order. Return the length of the longest subsequence in which each value is strictly larger than the one before.

  • 1 ≤ nums.length ≤ 2500
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • the page’s follow-up asks for O(n log n) time

The signature is function lengthOfLIS(nums: number[]): number. Try it on LeetCode first.

Hint

For each position, find the longest increasing subsequence that ends exactly there. Which earlier positions can come right before it?

Interviewer: Find the longest increasing subsequence.

Candidate: Strictly increasing, so two equal values can’t follow each other? And may I skip values, or must it be a contiguous run?

Interviewer: Strictly. And yes, skip any values you like.

Candidate: Only the length? Then here are my cases.

nums                  expected
[3, 1, 8, 2, 5]       3       1, 2, 5
[5]                   1
[9, 7, 5, 3]          1       decreasing
[4, 4, 4]             1       equal values don't chain
[3, 4, 1]             2       the longest doesn't end at the last value

Candidate: Let endingAt(i) be the longest one that ends with nums[i]. The value before it is some smaller nums[j] with j < i, and the part up to j is the best that ends at j. So endingAt(i) is 1 plus the largest endingAt(j) over those j, and the answer is the largest endingAt(i).

// Time O(2^n): on an increasing array endingAt(i) calls every endingAt(j) with j < i, so
// calls(i) = 1 + calls(0) + ... + calls(i - 1) = 2^i. Memory O(n): the call stack.
export function lengthOfLISRecursive(nums: number[]): number {
  function endingAt(i: number): number {
    let longest = 1;
    for (let j = 0; j < i; j++) {
      if (nums[j] < nums[i]) longest = Math.max(longest, 1 + endingAt(j));
    }
    return longest;
  }
  let best = 0;
  for (let i = 0; i < nums.length; i++) best = Math.max(best, endingAt(i));
  return best;
}

Candidate: On an increasing list, endingAt(i) calls every endingAt(j) before it, so the calls double with each value: O(2ⁿ). At 2,500 values it never finishes. The repeat is endingAt(j), solved again inside every later endingAt(i).

Candidate: The state is one index. With a memo, each endingAt(i) is solved once and scans the i values before it: O(n²), about 6.25 × 10⁶ steps at the limit, which fits. As a table it’s two loops.

The lab has the memo as lengthOfLISMemo. Its top-level loop asks for endingAt(0), endingAt(1) and so on in order, so every answer a call needs is saved already, and the stack stays two calls deep.

// Time O(n^2): two nested loops. Memory O(n): one cell per index.
// No one-row step: cell i can need any earlier cell, so the whole row stays.
export function lengthOfLISTable(nums: number[]): number {
  const endingAt: number[] = new Array(nums.length).fill(1);
  let best = 0;
  for (let i = 0; i < nums.length; i++) {
    for (let j = 0; j < i; j++) {
      if (nums[j] < nums[i]) endingAt[i] = Math.max(endingAt[i], endingAt[j] + 1);
    }
    best = Math.max(best, endingAt[i]);
  }
  return best;
}

Candidate: For [3, 1, 8, 2, 5] the cells are 1, 1, 2, 2, 3, and the answer is the largest cell, 3. The cells can’t shrink to a few numbers, because cell i may read any earlier cell.

In atlimit.ts, lengthOfLISTable took 7.7 ms on 2,500 random values.

Interviewer: It fits. The page asks for O(n log n), though.

Candidate: Then I’d keep a different fact. For each length, I keep the smallest value that an increasing subsequence of that length can end with so far. A smaller end is always at least as good, because more later values can follow it.

This method is patience sorting, named after a card game. You deal the values one by one onto piles. Each value goes on the leftmost pile whose top is greater than or equal to it, or on a new pile at the right.

Aldous and Diaconis (1999) prove that the number of piles is the length of the longest increasing subsequence. The tops, read left to right, are the smallest ends the Candidate described.

Candidate: The tops stay sorted from left to right, so a binary search finds the pile. It’s the first top that’s at least the value, the lower bound from Module 5. If there’s none, the value starts a new pile.

// Patience sorting (Aldous and Diaconis 1999, Lemma 1): deal the numbers onto piles, each on the
// leftmost pile whose top is >= it, or on a new pile at the right. The number of piles is the answer.
// tops[k] = the smallest possible last value of an increasing subsequence of length k + 1; it stays
// sorted, so a binary search finds the pile.
// Time O(n log n): n binary searches over at most n tops. Memory O(n): the tops.
function lengthOfLIS(nums: number[]): number {
  const tops: number[] = [];
  for (const value of nums) {
    let low = 0;
    let high = tops.length; // find the first top >= value, or tops.length if there is none
    while (low < high) {
      const middle = low + Math.floor((high - low) / 2);
      if (tops[middle] < value) low = middle + 1;
      else high = middle;
    }
    tops[low] = value; // replaces that top, or starts a new pile when low === tops.length
  }
  return tops.length;
}

export { lengthOfLIS };

Pause and predict. Deal [3, 1, 8, 2, 5]. What are the tops after each value?

Figure 6 shows the deal. Each row is one value, the pile it goes on, and the tops after it.

value   pile   tops after
3       0      [3]          new pile
1       0      [1]          1 <= 3: replaces 3
8       1      [1, 8]       new pile
2       1      [1, 2]       2 <= 8: replaces 8
5       2      [1, 2, 5]    new pile: 3 piles, the answer

Figure 6: 2 replaces 8 because a subsequence of length 2 that ends at 2 can be extended by more values, and that lets 5 start a third pile.

Candidate: For [4, 4, 4], every 4 finds the first top that’s at least 4 on pile 0 and replaces it, so there’s one pile.

The number of piles equals the answer, for two reasons. First, a pile’s top only gets smaller, so the values of an increasing subsequence land on different piles, each to the right of the one before. So there are at least as many piles as the longest length.

Second, each value placed on pile p can point to the top of pile p − 1 at that moment, which is smaller and came earlier. Following those pointers back from the last pile gives an increasing subsequence with one value per pile (Lemma 1 in the paper).

The paper states the lemma for distinct values. With repeats, the rule “greater than or equal to” puts an equal value on the same pile, so equal values never extend each other. That’s the strict version this problem asks for, and our lab tests check it against every subsequence of 300 random lists.

Interviewer: Final cost?

Candidate: O(n log n) time: n binary searches over at most n tops. O(n) memory for the tops. In atlimit.ts it took 0.5 ms on 2,500 random values.

Interviewer: Can you return the subsequence itself?

The Candidate’s answer

Candidate: The tops aren’t the subsequence. For each value, I’d also save the index of the top of the pile to its left when it was placed. Walking those back from the last pile’s top gives the subsequence in reverse, still in O(n log n).

This version isn’t in the lab.

Interviewer: And if equal values may follow each other?

The Candidate’s answer

Candidate: Then an equal value should start the next pile, not share one. I’d search for the first top greater than the value, the upper bound, instead of the lower bound.

Three mistakes are common here.

  • Returning the last cell of the table. For [3, 4, 1] it returns 1 instead of 2: the longest doesn’t have to end at the last value. Return the largest cell.
  • The upper bound in patience sorting. Searching for the first top greater than the value puts equal values on new piles. For [7, 7, 7] it returns 3 instead of 1. Search for the first top greater than or equal to it.
  • Reading the tops as the subsequence. For [3, 4, 1, 2, 0] the tops end as [0,2], but 0 comes after 2 in the list. Only the length, 2, is right.

Lab folder: module-11/0300-longest-increasing-subsequence/ in the course repository.

139. Word Break

139. Word Break is rated Medium. You get a string and a list of words. Decide whether the string can be cut into pieces that are each a word from the list. A word may be used any number of times.

  • 1 ≤ s.length ≤ 300
  • 1 ≤ wordDict.length ≤ 1000
  • 1 ≤ wordDict[i].length ≤ 20
  • only lowercase English letters; the words are all different

The signature is function wordBreak(s: string, wordDict: string[]): boolean. Try it on LeetCode first.

Hint

Can the first i letters be cut into words? That’s true if some earlier cut is good and the letters between it and i form a word.

Interviewer: Can the string be cut into dictionary words?

Candidate: May a word be used twice? Must the pieces cover every letter? And do you want the cut, or only yes or no?

Interviewer: Yes, yes, and only yes or no.

Candidate: Words have at most 20 letters, so a piece starts at most 20 letters back. Here are my cases.

s           wordDict                  expected
"bluebird"  ["blue", "bird", "bl"]    true    blue + bird
"a"         ["b"]                     false
"aaaa"      ["a"]                     true    one word, four times
"abcd"      ["a", "abc", "b", "cd"]   true    a + b + cd; "abc" first fails
"aaaab"     ["a", "aa"]               false   every cut fails at the b

Candidate: The plain recursion: from a start position, try every end. If the piece is a word and the rest can be cut, the answer is yes.

// Time O(2^n) in the worst case: on "aaa...ab" with words "a", "aa", "aaa", ... every way of cutting
// the a's is tried and every one fails at the b. Memory O(n): the call stack.
export function wordBreakRecursive(s: string, wordDict: string[]): boolean {
  const words = new Set(wordDict);
  function canBreakFrom(start: number): boolean {
    if (start === s.length) return true;
    for (let end = start + 1; end <= s.length; end++) {
      if (words.has(s.slice(start, end)) && canBreakFrom(end)) return true;
    }
    return false;
  }
  return canBreakFrom(0);
}

Candidate: On "aaaab" with every run of a’s as a word, every way to cut the a’s is tried, and each one fails at the b. That’s O(2ⁿ), so 300 letters never finish. The repeat: canBreakFrom(i) is asked once for every way to reach i, and its answer never changes.

Candidate: The state is the start position. With a memo, each start is solved once, tries n ends, and copies a slice of up to n letters for each. That’s O(n³), about 2.7 × 10⁷ at 300, and it fits.

The lab has it as wordBreakMemo, and in atlimit.ts it took 8.7 ms on "a" × 299 + "b".

Candidate: As a table I can also use the word length: only the last 20 cuts can start a word that ends here.

// canBreak[i]: the first i letters can be cut into words. Only lengths that some word has are
// tried, so each cell costs at most L slices of at most L letters (L = longest word, 20 here).
// Time O(n * L^2) for the slices and hashes. Memory O(n + total dictionary length).
// No one-row step worth making: cell i needs cells up to L back.
function wordBreak(s: string, wordDict: string[]): boolean {
  const words = new Set(wordDict);
  let longestWord = 0;
  for (const word of wordDict) longestWord = Math.max(longestWord, word.length);
  const canBreak: boolean[] = new Array(s.length + 1).fill(false);
  canBreak[0] = true; // the empty prefix needs no words
  for (let end = 1; end <= s.length; end++) {
    for (let start = Math.max(0, end - longestWord); start < end; start++) {
      if (canBreak[start] && words.has(s.slice(start, end))) {
        canBreak[end] = true;
        break;
      }
    }
  }
  return canBreak[s.length];
}

export { wordBreak };

Interviewer: Trace "bluebird".

Figure 7 shows canBreak after the loop: index i is T when the first i letters can be cut into words. The longest word has 4 letters, so each end looks back at most 4 positions.

s:        b   l   u   e   b   i   r   d
index:  0   1   2   3   4   5   6   7   8
        T   F   T   F   T   F   F   F   T
                ^bl     ^blue           ^bird (from index 4)

Figure 7: index 2 is true through “bl”, but nothing starts a word at “u”, so only the cut at 4 leads to the end.

Candidate: For "aaaab" with ["a", "aa"], indexes 0 to 4 are true and index 5 stays false, because no word ends with b.

Interviewer: Final cost?

Candidate: O(n · L²) time with L = 20: each cell tries up to L starts, and each slice and hash costs up to L letters. O(n) memory plus the word set. Keeping only the last 21 cells would work, but the string is already O(n), so it doesn’t pay.

In atlimit.ts, wordBreak took 0.1 ms on the worst case.

Interviewer: What if I want every sentence, not yes or no?

The Candidate’s answer

Candidate: Then I’d backtrack, as in Module 10, and use a table of positions that can reach the end to skip the others. The output itself can be exponential in size, so no method is fast on every input.

That’s LeetCode’s 140. Word Break II, which this course doesn’t cover. This version isn’t in the lab.

Interviewer: What if the words were long?

The Candidate’s answer

Candidate: I’d put the words in a trie, as in Module 10’s 208, and walk it from each good start, one letter at a time. Each step is one child lookup, with no slices, and the walk stops at the first missing letter.

This version isn’t in the lab.

One mistake is common here.

  • The longest matching word first, with no going back. For "abcd" with ["a", "abc", "b", "cd"] it returns false instead of true: after “abc”, the “d” is no word. Try every cut that ends at a good position.

Lab folder: module-11/0139-word-break/ in the course repository.

62. Unique Paths

62. Unique Paths is rated Medium. A grid has m rows and n columns. Count the routes from the top-left cell to the bottom-right cell when each move goes one cell down or one cell right.

  • 1 ≤ m, n ≤ 100
  • the test cases keep the answer at or below 2 × 10⁹

The signature is function uniquePaths(m: number, n: number): number. Try it on LeetCode first.

Hint

The last move into a cell came from above or from the left.

Interviewer: Count the paths from corner to corner, moving only down or right.

Candidate: Are any cells blocked? And how large can the answer get?

Interviewer: No blocked cells. The answer is at most 2 × 10⁹.

Candidate: Then a Number holds it exactly. Here are my cases.

m x n      expected
3 x 3      6             two downs and two rights, in any order
1 x 1      1             already there
1 x 100    1             one straight line
17 x 17    601,080,390   near the answer limit

Candidate: paths(r, c) = paths(r − 1, c) + paths(r, c − 1), and every cell on the top row or left column has one path.

// Time O(C(m + n - 2, m - 1)): the calls end in one base case per path, so there are about
// 2 * answer calls, up to about 4 * 10^9 at the limits. Memory O(m + n): the call stack.
export function uniquePathsRecursive(m: number, n: number): number {
  function paths(row: number, col: number): number {
    if (row === 0 || col === 0) return 1;
    return paths(row - 1, col) + paths(row, col - 1);
  }
  return paths(m - 1, n - 1);
}

Candidate: Each path ends in one base case that returns 1, so the calls are about twice the answer: up to 4 × 10⁹.

In atlimit.ts, uniquePathsRecursive(17, 17) took 3,217.4 ms for 601,080,390 paths. The limit allows answers more than three times larger, so it’s too slow.

Candidate: The repeat: paths(r, c) is solved once for each route that reaches it. The state is (r, c), so a memo or a table of m × n cells covers it. The table fills row by row, because a cell reads the one above and the one to its left.

// Time O(m * n): one pass over the grid. Memory O(m * n): the table.
export function uniquePathsTable(m: number, n: number): number {
  const paths: number[][] = Array.from({ length: m }, () => new Array(n).fill(1));
  for (let row = 1; row < m; row++) {
    for (let col = 1; col < n; col++) paths[row][col] = paths[row - 1][col] + paths[row][col - 1];
  }
  return paths[m - 1][n - 1];
}

Candidate: A row reads only the row above, so one row is enough. Before I update rowPaths[col], it still holds the cell above, and rowPaths[col - 1] already holds the cell to the left in this row. So the update is one addition.

// Time O(m * n). Memory O(n): one row. Before the update, rowPaths[col] still holds the cell
// above; rowPaths[col - 1] already holds the cell to the left in this row.
function uniquePaths(m: number, n: number): number {
  const rowPaths: number[] = new Array(n).fill(1);
  for (let row = 1; row < m; row++) {
    for (let col = 1; col < n; col++) rowPaths[col] += rowPaths[col - 1];
  }
  return rowPaths[n - 1];
}

export { uniquePaths };

Interviewer: Trace 3 × 3.

Figure 8 shows rowPaths after each row.

row 0:   [1, 1, 1]    the top row: one path to each cell
row 1:   [1, 2, 3]    2 = 1 above + 1 left;  3 = 1 above + 2 left
row 2:   [1, 3, 6]    3 = 2 + 1;             6 = 3 above + 3 left

Figure 8: each new value is the old value in the same place (the cell above) plus the new value to its left, so one row is rewritten in place.

Candidate: For 1 × 100 the outer loop never runs, and the row of 1s gives 1.

Interviewer: Final cost?

Candidate: O(m · n) time, O(n) memory. In atlimit.ts, uniquePaths(17, 17) took under 0.1 ms.

Interviewer: Can you do it without a table?

The Candidate’s answer

Candidate: A path is m − 1 downs and n − 1 rights in some order. So the count is the number of ways to choose which moves are downs, C(m + n − 2, m − 1). I multiply and divide one step at a time, so every value along the way is a whole number.

// Time O(min(m, n)), memory O(1): a path is m - 1 downs and n - 1 rights in some order, so the count
// is C(m + n - 2, k) with k = min(m, n) - 1. After step i, result = C(m + n - 2 - k + i, i), a whole
// number, and result * (next factor) stays below 2 * 10^9 * 199, far under 2^53, so it is exact.
export function uniquePathsFormula(m: number, n: number): number {
  const moves = m + n - 2;
  const k = Math.min(m, n) - 1;
  let result = 1;
  for (let i = 1; i <= k; i++) result = (result * (moves - k + i)) / i;
  return result;
}

Candidate: O(min(m, n)) time and O(1) memory. Every product stays below 2 × 10⁹ × 199, far under 2⁵³, so the division is exact.

Interviewer: What if some cells are blocked?

The Candidate’s answer

Candidate: A blocked cell holds 0, and the same one-row loop works. The top row and left column are 1 only up to the first blocked cell, and 0 after it.

That’s LeetCode’s 63. Unique Paths II, which this course doesn’t cover; DSA Module 11 has it as an exercise. This version isn’t in this course’s lab.

Two mistakes are common here.

  • The top row filled with 0. For 3 × 3 it returns 3 instead of 6. There’s one path to each cell of the top row and the left column.
  • Counting lines instead of cells. Calling paths(m, n) instead of paths(m − 1, n − 1) counts a grid one larger each way. For 3 × 3 it returns 20 instead of 6.

Lab folder: module-11/0062-unique-paths/ in the course repository.

1143. Longest Common Subsequence

1143. Longest Common Subsequence is rated Medium. Given two strings, find the longest sequence of letters that is a subsequence of both: it can be read in order in each, with letters skipped freely. Return its length, or 0 if they share no letter.

  • 1 ≤ text1.length, text2.length ≤ 1000
  • only lowercase English letters

The signature is function longestCommonSubsequence(text1: string, text2: string): number. Try it on LeetCode first.

Hint

Compare the last letters of the two prefixes. If they match, use them. If not, one of the two isn’t in the answer.

Interviewer: Find the longest common subsequence of two strings.

Candidate: Subsequence, so letters can be skipped, not a substring? And only the length?

Interviewer: Yes to both. Each string has at least one letter.

Candidate: Up to 1,000 letters each, so a table of every pair of prefixes is 10⁶ cells. Here are my cases.

text1      text2      expected
"deploy"   "replay"   4      e, p, l, y
"abc"      "def"      0      no common letter
"abc"      "cba"      1
"x"        "x"        1      equal strings give their length

Candidate: Let lcs(i, j) be the answer for the first i letters of text1 and the first j of text2. If the last letters match, using them never hurts: lcs(i − 1, j − 1) + 1. If they don’t, at least one of them isn’t in the answer, so I take the larger of dropping either.

// Time O(2^(m + n)): on a mismatch each call makes two more, and each call shortens one string
// by one letter. Memory O(m + n): the call stack.
export function longestCommonSubsequenceRecursive(text1: string, text2: string): number {
  function lcs(i: number, j: number): number {
    if (i === 0 || j === 0) return 0;
    if (text1[i - 1] === text2[j - 1]) return lcs(i - 1, j - 1) + 1;
    return Math.max(lcs(i - 1, j), lcs(i, j - 1));
  }
  return lcs(text1.length, text2.length);
}

Candidate: On strings with no common letter, every call makes two more until one string is empty: O(2^(m+n)). At 1,000 + 1,000, never. lcs(i − 1, j − 1) is reached through both lcs(i − 1, j) and lcs(i, j − 1), so the state (i, j) repeats.

Candidate: The memo, longestCommonSubsequenceMemo in the lab, is O(m · n), and its chain of calls is at most m + n = 2,000 deep. That fits: stack-depth.ts found 6,207 calls on a first call. But the table needs no stack at all, and row i reads only row i − 1, so I’d write it with two rows.

// Time O(m * n). Memory O(n): row i needs only row i - 1, so keep two rows of n + 1 cells.
// (Pass the shorter string as text2 to get O(min(m, n)).)
function longestCommonSubsequence(text1: string, text2: string): number {
  const n = text2.length;
  let previous: number[] = new Array(n + 1).fill(0);
  let current: number[] = new Array(n + 1).fill(0);
  for (let i = 1; i <= text1.length; i++) {
    for (let j = 1; j <= n; j++) {
      if (text1[i - 1] === text2[j - 1]) current[j] = previous[j - 1] + 1;
      else current[j] = Math.max(previous[j], current[j - 1]);
    }
    [previous, current] = [current, previous];
  }
  return previous[n];
}

export { longestCommonSubsequence };

Candidate: After each row, I swap the two arrays, so previous is always the row finished last. Cell 0 of each row is never written, so it stays 0, the empty prefix. The full table is longestCommonSubsequenceTable in the lab.

Interviewer: Trace your example.

Figure 9 shows the full table for "deploy" (rows) and "replay" (columns). The two-row version holds two of these rows at a time.

          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: each match (e, p, l, y) adds 1 to the cell up and to the left, and each mismatch copies the larger of up and left.

Candidate: For "abc" and "def" no letter matches, so every cell is the larger of two zeros.

Interviewer: Final cost?

Candidate: O(m · n) time, 10⁶ cells at the limit. O(n) memory for two rows. In atlimit.ts, on two random strings of 1,000 letters, longestCommonSubsequence took 7.3 ms, the full table 14.6 ms and the memo 22.8 ms.

Interviewer: Can you return the subsequence?

The Candidate’s answer

Candidate: I’d keep the full table and walk back from the corner. On a match, I take the letter and go up and left; otherwise I go toward the larger of up and left. That needs the O(m · n) table, about 8 MB here.

This version isn’t in the lab.

Interviewer: How does this relate to editing one string into the other?

The Candidate’s answer

Candidate: If only inserts and deletes are allowed, I keep the common subsequence and delete or insert everything else: m + n − 2 × LCS edits. With replacements too, that’s problem 72, next.

Two mistakes are common here.

  • The diagonal on a mismatch. For "ab" and "ba" it returns 0 instead of 1. On a mismatch, take the larger of up and left.
  • The left neighbor from the previous row. With two rows, Math.max(previous[j], previous[j - 1]) reads the old row twice. For "abcd" and "acbd" it returns 2 instead of 3. The left cell is current[j - 1].

Lab folder: module-11/1143-longest-common-subsequence/ in the course repository.

72. Edit Distance

72. Edit Distance is rated Medium. You can change a string with three edits, each on one letter: insert a letter, delete one, or replace one with another. Return the fewest edits that turn word1 into word2. That number is the edit distance between them, also called the Levenshtein distance.

  • 0 ≤ word1.length, word2.length ≤ 500
  • only lowercase English letters

The signature is function minDistance(word1: string, word2: string): number. Try it on LeetCode first.

Hint

Same table as 1143. If the last letters differ, the last edit was one of three. Which smaller pair of prefixes does each leave?

Interviewer: Find the fewest edits that turn one word into the other.

Candidate: Does every edit cost 1? And can a word be empty?

Interviewer: Every edit costs 1. Either word, or both, can be empty.

Candidate: Then the first row and column are the empty cases: turning “” into j letters is j inserts. Here are my cases.

word1        word2        expected
"flaw"       "lawn"       2      delete f, insert n
"cart"       "chart"      1      insert h
""           "abc"        3      three inserts
"same"       "same"       0
500 a's      500 b's      500    replace each

Candidate: Let edits(i, j) be the answer for the first i and j letters. If either prefix is empty, it’s the other’s length, and if the last letters match, they cost nothing: edits(i − 1, j − 1).

Candidate: If they don’t match, the last edit was a delete (i − 1, j), an insert (i, j − 1) or a replace (i − 1, j − 1), plus 1.

// Time O(3^(m + n)): on a mismatch each call makes three more. Memory O(m + n): the call stack.
export function minDistanceRecursive(word1: string, word2: string): number {
  function edits(i: number, j: number): number {
    if (i === 0) return j;
    if (j === 0) return i;
    if (word1[i - 1] === word2[j - 1]) return edits(i - 1, j - 1);
    return 1 + Math.min(edits(i - 1, j), edits(i, j - 1), edits(i - 1, j - 1));
  }
  return edits(word1.length, word2.length);
}

Candidate: On a mismatch it makes three calls, so O(3^(m+n)). At 500 + 500, never. edits(i − 1, j − 1) is reached three ways.

Candidate: The memo, minDistanceMemo, is O(m · n) with a chain of at most 1,000 calls, which fits. The table is the same grid as 1143, with row 0 and column 0 set to 0, 1, 2 and so on. And again a row reads only the row above, so two rows are enough.

// Time O(m * n). Memory O(n): row i needs only row i - 1, so keep two rows of n + 1 cells.
function minDistance(word1: string, word2: string): number {
  const n = word2.length;
  let previous: number[] = Array.from({ length: n + 1 }, (_, j) => j); // row 0: j inserts
  let current: number[] = new Array(n + 1).fill(0);
  for (let i = 1; i <= word1.length; i++) {
    current[0] = i; // i deletes
    for (let j = 1; j <= n; j++) {
      if (word1[i - 1] === word2[j - 1]) current[j] = previous[j - 1];
      else current[j] = 1 + Math.min(previous[j], current[j - 1], previous[j - 1]);
    }
    [previous, current] = [current, previous];
  }
  return previous[n];
}

export { minDistance };

Candidate: Unlike 1143, cell 0 changes from row to row, so I set current[0] = i at the start of each row.

Interviewer: Trace "flaw" to "lawn".

Figure 10 shows the full table, with word1 down the side. The two-row version holds two of these rows at a time.

          l   a   w   n
      0   1   2   3   4
  f   1   1   2   3   4
  l   2   1   2   3   4
  a   3   2   1   2   3
  w   4   3   2   1   2

Figure 10: deleting f costs 1 (column l, row l), the matches l, a, w keep it at 1 along the diagonal, and inserting n makes the corner 2.

Candidate: For "" to "abc", the loop never runs and previous is row 0, so the answer is 3.

Interviewer: Final cost?

Candidate: O(m · n) time, O(n) memory. In atlimit.ts, on two random words of 500 letters, minDistance took 3.5 ms, the full table 5.0 ms and the memo 8.0 ms.

Interviewer: What if I only need to know whether the distance is at most k?

The Candidate’s answer

Candidate: A cell more than k away from the diagonal is already more than k edits, because the two prefixes differ in length by more than k. So I’d fill only a band of 2k + 1 cells per row: O(k · n).

This version isn’t in the lab.

Interviewer: What if a replace costs 2 and the other edits 1?

The Candidate’s answer

Candidate: Same table. I’d add each edit’s own cost instead of a shared 1: previous[j] + 1, current[j - 1] + 1 and previous[j - 1] + 2.

This version isn’t in the lab.

One mistake is common here.

  • Row 0 and column 0 left at 0. Turning a word into “” then looks free. "abc" to "" returns 0 instead of 3, and "sit" to "it" returns 0 instead of 1. Row 0 is j inserts and column 0 is i deletes.

Lab folder: module-11/0072-edit-distance/ in the course repository.

Measured: Coin Change, plain recursion against a memo and a table

This measurement checks the opening’s claim that plain recursion grows exponentially with the amount, and the memo and the table grow linearly. Plain recursion’s cost depends on the coins as much as on the amount, so its runs use the same coins, [1, 2, 5], at every size. The table’s runs at large amounts use 12 random coins from 1 to 500.

// measure.ts: Module 11's measurement. 322. Coin Change, plain recursion against the memo and the table.
// Run from the repository root: node module-11/measure.ts
import { bench } from "../shared/bench.ts";
import { coinChangeRecursive, coinChangeMemo, coinChange } from "./0322-coin-change/solution.ts";

let sink = 0;

// Plain recursion's cost depends on the coins as much as on the amount, so its runs use the same
// coins, [1, 2, 5]; only the amount grows. The table's runs use 12 random coins.
const smallCoins = [1, 2, 5];
const randomCoins = () => Array.from({ length: 12 }, () => 1 + Math.floor(Math.random() * 500));

// Calls plain recursion makes: calls(a) = 1 + the sum of calls(a - c) over coins c <= a. Exact, in BigInt.
function recursiveCalls(coins: number[], amount: number): bigint {
  const calls: bigint[] = [];
  for (let a = 0; a <= amount; a++) {
    calls[a] = 1n;
    if (a > 0) for (const c of coins) if (c <= a) calls[a] += calls[a - c];
  }
  return calls[amount];
}

bench("coinChangeRecursive, coins [1, 2, 5], amount n", [26, 30, 34], (n) => n, (n) => (sink += coinChangeRecursive(smallCoins, n)));
bench("coinChangeMemo, coins [1, 2, 5], amount n", [26, 30, 34], (n) => n, (n) => (sink += coinChangeMemo(smallCoins, n)));
bench("coinChange (table), coins [1, 2, 5], amount n", [26, 30, 34], (n) => n, (n) => (sink += coinChange(smallCoins, n)));
bench("coinChange (table), 12 random coins in 1..500, amount n", [1_000, 10_000, 100_000], (n) => ({ coins: randomCoins(), n }), ({ coins, n }) => (sink += coinChange(coins, n)));

console.log("\ncalls plain recursion makes with coins [1, 2, 5]:");
for (const amount of [26, 30, 34, 100, 10_000]) {
  const calls = recursiveCalls(smallCoins, amount);
  const text = calls.toString();
  console.log(`  amount ${amount.toLocaleString("en-US")}: ${text.length > 20 ? `about 10^${text.length - 1}` : BigInt(text).toLocaleString("en-US")}`);
}
console.log(`  per +4 of amount, near 34: x${(Number(recursiveCalls(smallCoins, 34)) / Number(recursiveCalls(smallCoins, 30))).toFixed(2)}`);
console.log(`\nsink ${sink}`);

bench runs each size once to warm up, then five times on fresh inputs, and prints the median and how many times slower each size is than the one before. recursiveCalls counts plain recursion’s calls in BigInt, with the same recurrence as the calls themselves, so it can count amounts that would never finish. sink adds up the answers, so V8 can’t skip the calls.

Pause and predict. Plain recursion goes from amount 30 to 34. By how much should its time grow, if the calls grow about 1.7 times per unit of amount?

Here is what node module-11/measure.ts printed:

coinChangeRecursive, coins [1, 2, 5], amount n
             n   median ms   x prev
            26        8.72         
            30       74.16      8.5
            34      625.40      8.4

coinChangeMemo, coins [1, 2, 5], amount n
             n   median ms   x prev
            26        0.01         
            30        0.01      1.2
            34        0.01      1.1

coinChange (table), coins [1, 2, 5], amount n
             n   median ms   x prev
            26        0.01         
            30        0.01      1.1
            34        0.01      1.3

coinChange (table), 12 random coins in 1..500, amount n
             n   median ms   x prev
         1,000        0.25         
        10,000        0.26      1.1
       100,000        2.94     11.2

calls plain recursion makes with coins [1, 2, 5]:
  amount 26: 1,576,824
  amount 30: 13,322,380
  amount 34: 112,559,020
  amount 100: about 10^23
  amount 10,000: about 10^2317
  per +4 of amount, near 34: x8.45

sink 1784

These numbers come from one run on an Apple M2 laptop with macOS and Node.js 24.22.1. Your numbers will differ, but the ratios should look alike.

Plain recursion grew 8.5 and 8.4 times for each 4 added to the amount, and its exact call count grows 8.45 times, about 1.7 per unit of amount. That’s exponential in the amount. At amount 34 it made 112,559,020 calls in 625.40 ms, about 5.6 ns per call. At amount 100 it would make about 2.2 × 10²³ calls, roughly 40 million years at that speed, and at LeetCode’s limit of 10⁴ the count has 2,318 digits.

The memo and the table stay at 0.01 ms for these amounts, because they fill only 27 to 35 cells. The table over larger amounts grew 11.2 times for 10 times the amount, from 10,000 to 100,000, as O(amount × k) predicts. The 1.1 from 1,000 to 10,000 shows fixed costs at the small end, not the work per cell. At LeetCode’s limit, 10⁴ with 12 coins, it took 0.26 ms.

So at amount 34, the same answer took 625.40 ms by plain recursion and 0.01 ms by the table. The memo is as fast as the table here, but at 10⁴ with a coin of 1 it throws RangeError, as the first follow-up of 322 showed.

Underneath: tables, stacks and exact numbers in JavaScript

A table in these solutions is a JavaScript array of Numbers. V8 keeps small integers packed in the array, and DSA Module 11 measured a 4,001 × 4,001 table at 8.01 bytes per cell. So the largest table in this module, 1143’s 1,001 × 1,001, is about 8 MB, and its two-row version keeps 2 × 1,001 numbers.

Every count here stays exact because it stays at or below Number.MAX_SAFE_INTEGER, 2⁵³ − 1 (ECMAScript, section 21.1.2.6). Climbing Stairs tops out at 1,836,311,903, and Unique Paths at 2 × 10⁹ by the page’s promise. Past 2⁵³ − 1 a Number answer is wrong with no error, and BigInt fixes it at the cost of not mixing with Numbers.

The top-down versions are limited by the call stack, not by memory. V8’s default --stack-size is 984 KB on this build, and in stack-depth.ts it held between 4,433 and 7,760 calls of these functions on a first call. So a memo whose chain can be 10⁴ long (Coin Change) fails, and chains of 2,000 or fewer (1143 at most) pass.

Coin Change’s memo fails sooner than the others, maybe because its frames are larger (a loop over the coins, more locals), but we didn’t measure frame sizes. DSA Module 6 covers the call stack limit, and DSA Module 11 covers memo against table and keeping one row.

Cheat sheet

Figure 11 maps each problem in this module to the sign that pointed to its solution.

sign                      no.   state: recurrence             cost, memory
ways, 1 or 2 steps        70    n: w(n-1) + w(n-2)            O(n), O(1)
best, no two neighbors    198   i: max(skip, take + i-2)      O(n), O(1)
fewest coins to a total   322   amount: 1 + min over coins    O(a·k), O(a)
longest rising, skips ok  300   piles: lower bound per value  O(n log n), O(n)
cut into dictionary words 139   prefix: good cut + a word     O(n·L²), O(n)
paths, down or right      62    cell: above + left            O(m·n), O(n)
common letters in order   1143  (i,j): diag + 1, else max     O(m·n), O(n)
fewest one-letter edits   72    (i,j): diag, else 1 + min     O(m·n), O(n)

Figure 11: each problem is one state and one recurrence; the cost is states times work per state, and the memory is the cells still read.

  • Steps: plain recursion, name the repeat, memo, table, fewer rows; say each cost.
  • Memo marker: a value no answer can take (−1, undefined), never a truthy check.
  • Stack: a memo’s chain can be as long as the state; past a few thousand, use the table.
  • Next: Module 12 works greedy and bit problems, starting from Maximum Subarray by summing every subarray, and ends with a full mock interview.

Sources