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

Module 9: Graphs

Work seven graph problems as spoken interviews, from rescanning a grid or a course list to one search that visits each node once.

Here is a first answer to 994. Rotting Oranges: every minute, scan the whole grid, collect the fresh oranges next to a rotten one, and rot them all.

// O((m·n)^2) time, O(m·n) memory: every minute, scan the whole grid for fresh oranges next to a rotten
// one, then rot them all. There can be about m·n / 2 minutes (a winding line of oranges).
export function orangesRottingRescan(grid: number[][]): number {
  const rows = grid.length;
  const cols = grid[0].length;
  const cells = grid.map((row) => [...row]);
  const isRotten = (r: number, c: number) => r >= 0 && r < rows && c >= 0 && c < cols && cells[r][c] === 2;
  let minutes = 0;
  while (true) {
    const toRot: [number, number][] = []; // collected first, so an orange rotted this minute rots nothing until the next
    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        if (cells[r][c] === 1 && (isRotten(r + 1, c) || isRotten(r - 1, c) || isRotten(r, c + 1) || isRotten(r, c - 1))) {
          toRot.push([r, c]);
        }
      }
    }
    if (toRot.length === 0) break;
    for (const [r, c] of toRot) cells[r][c] = 2;
    minutes++;
  }
  return cells.some((row) => row.includes(1)) ? -1 : minutes;
}

LeetCode’s grid is at most 10 × 10, and at that size this answer is fine. The slowest grid the limits allow is a line of oranges winding through every row. It needs about 60 scans of 100 cells, and it took 0.4 ms (atlimit.ts in the module folder). The case against the rescan is how it grows. In the measurement at the end of this page, it took 744.69 ms on a 400 × 400 grid, where a search that touches each orange once took 8.51 ms.

This module works seven graph problems. Four are grids, where each cell is a node; two are courses with prerequisites; one is a list of words. Each one follows the nine steps from Module 1. Two of them end with the follow-up Module 7 asked about trees: what if the recursion goes deeper than Node.js’s call stack?

After this module, you can:

  • count the regions of a grid with DFS or BFS, marking each cell once, and tell when a recursive DFS will overflow Node.js’s call stack
  • start a BFS from many cells at once to get each cell’s distance to the nearest one, and turn a question around to search from the target
  • copy a graph with a Map from each original node to its copy
  • decide whether prerequisites contain a cycle, and list an order that takes every course, with Kahn’s algorithm
  • find the fewest steps between two words by generating each word’s neighbours instead of comparing it with every other word

The code for this module is in module-09/ of the course repository, and node --test "module-09/**/*.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: a search that visits each node once

A graph is a set of nodes joined by edges. In an undirected graph an edge goes both ways, like two cells that touch. In a directed graph it goes one way, like “take course 0 before course 1”. We write V for the number of nodes and E for the number of edges. DSA Module 7 teaches graphs, and builds the searches this module uses.

In a grid problem, each cell is a node, and its edges go to the cells above, below, left and right. Nobody stores those edges; the code computes them from (r, c). A graph whose edges you compute instead of store is an implicit graph. Figure 1 shows how the lab numbers a grid’s cells, so that one number stands for one cell.

cols = 4             cell (r, c) is number r * cols + c

       c=0  c=1  c=2  c=3          the neighbours of cell 5, at (1, 1):
r=0     0    1    2    3             down   (2, 1) = 9
r=1     4   [5]   6    7             up     (0, 1) = 1
r=2     8    9   10   11             right  (1, 2) = 6
                                     left   (1, 0) = 4

Figure 1: a grid is a graph whose edges you compute from (r, c), and one number per cell lets one array mark every cell.

Module 7 defined depth-first search (DFS), which goes as deep as it can before it backs up, and breadth-first search (BFS), which visits everything one step away, then two steps, and so on. On a tree, each node is reached once. On a graph, a node can be reached again through a loop or a second path. So every search here keeps a visited mark per node, and marks a node the first time it reaches it. Then each node is handled once and each edge read once or twice: O(V + E) time.

The lab keeps those marks in a Uint8Array, an array of bytes that starts as all zeros, indexed by the cell or course number. Its BFS queue is a plain array read with a head index, never shift(). The section “Underneath” at the end of this page says why.

Signs that point to a graph search:

  • a grid of cells, and “connected”, “region”, “island”, “reach”
  • “the fewest steps” or “how many minutes”, when every step costs the same: BFS
  • prerequisites, dependencies, “an order that respects”: a directed graph with no loop
  • objects that link to each other, to copy or to walk
  • words, states or positions where one small change is one step

The cost is memory: O(V) for the marks and the queue. A recursive DFS also keeps one call waiting per node on its current path, and on a grid that path can hold every cell.

Rule: Turn the input into nodes and edges, mark each node the first time you reach it, and use BFS when you need the fewest steps.

200. Number of Islands

200. Number of Islands is rated Medium. You get a grid of land and water, as the strings "1" and "0". Land cells that share a side belong to the same island; cells that touch only at a corner don’t. Return the number of islands.

  • m rows and n columns, 1 ≤ m, n ≤ 300 (up to 90,000 cells)
  • every cell is "1" or "0"
  • everything outside the grid counts as water

The signature is function numIslands(grid: string[][]): number. Try it on LeetCode first.

Hint

When you find a land cell nobody has counted yet, you’ve found a new island. How do you stop its other cells from being counted again?

Interviewer: Count the islands in this grid.

Candidate: So land cells that touch form one island, and I return how many islands there are. Do cells that touch only at a corner join?

Interviewer: No. Only up, down, left and right.

Candidate: May I change the grid, for example turn land I’ve visited into water?

Interviewer: Leave it unchanged.

Candidate: Can the grid be empty? And the cells are strings, not numbers?

Interviewer: It has at least one row and one column. The cells are the strings "1" and "0".

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

Candidate: Here’s my example and three edge cases. I write each row as a string.

grid (rows)              expected
1100 0101 1001 0011      3      (2,0) touches (1,1) only at a corner
00 00                    0      all water
101 010 101              5      corners don't join
300 x 300, all land      1      one island of 90,000 cells

Figure 2 draws the example, with one letter for each island’s cells.

        c=0  c=1  c=2  c=3
r=0      A    A    .    .
r=1      .    A    .    B
r=2      C    .    .    B
r=3      .    .    B    B

Figure 2: three islands; C touches A only at a corner, so it’s an island of its own.

Candidate: The naive answer: from every land cell, walk its whole island with a fresh visited array. I count the island only when the start is its smallest-numbered cell, so each island counts once.

// O((m·n)^2) time, O(m·n) memory: from every land cell, a fresh search walks its whole island and
// counts the island only if no cell in it has a smaller number. One big island is walked once per cell.
export function numIslandsSearchPerCell(grid: string[][]): number {
  const rows = grid.length;
  const cols = grid[0].length;
  let islands = 0;
  for (let start = 0; start < rows * cols; start++) {
    if (grid[Math.floor(start / cols)][start % cols] !== "1") continue;
    const seen = new Uint8Array(rows * cols); // a new visited set for every search
    seen[start] = 1;
    const queue = [start];
    let smallest = start;
    for (let head = 0; head < queue.length; head++) {
      const cell = queue[head];
      smallest = Math.min(smallest, cell);
      const r = Math.floor(cell / cols);
      const c = cell % cols;
      for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
        if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
        const next = nr * cols + nc;
        if (grid[nr][nc] === "1" && !seen[next]) {
          seen[next] = 1;
          queue.push(next);
        }
      }
    }
    if (smallest === start) islands++;
  }
  return islands;
}

Candidate: One search can walk every cell, and there’s one search per land cell, so it’s O((m·n)²) time. Memory is O(m·n) for the visited array and the queue.

Candidate: At 300 × 300 of land, that’s 90,000 searches of 90,000 cells, about 8 × 10⁹ steps, 80 times the budget.

atlimit.ts times it below the limit, on grids of all land. It took 1,506.9 ms at 75 × 75 and 24,548.8 ms at 150 × 150: 16 times longer for 4 times the cells, as O((m·n)²) predicts. Another 16 times at 300 × 300 would be over six minutes, so we didn’t run it.

Interviewer: What does it repeat?

Candidate: It walks each island once for every cell in it. If all the searches share one visited array, each cell is walked once in total. I scan the grid, and every land cell I meet that isn’t marked yet starts a new island: I count it and mark the whole island.

Candidate: To mark an island, I’ll write a recursive DFS that marks a cell and then calls itself on the four neighbours.

// O(m·n) time, O(m·n) memory, but one call stack frame per cell on the current path:
// a recursive DFS with one visited set shared by every search. Overflows the stack on big islands.
export function numIslandsDfs(grid: string[][]): number {
  const rows = grid.length;
  const cols = grid[0].length;
  const seen = new Uint8Array(rows * cols);

  function sink(r: number, c: number): void {
    if (r < 0 || r >= rows || c < 0 || c >= cols) return;
    if (grid[r][c] !== "1" || seen[r * cols + c]) return;
    seen[r * cols + c] = 1;
    sink(r + 1, c);
    sink(r - 1, c);
    sink(r, c + 1);
    sink(r, c - 1);
  }

  let islands = 0;
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] === "1" && !seen[r * cols + c]) {
        islands++;
        sink(r, c);
      }
    }
  }
  return islands;
}

Candidate: sink returns at once outside the grid, on water, and on a cell that’s already marked. So each land cell is marked once, by the first call that reaches it.

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

Interviewer: Trace your example.

Figure 3 follows the scan row by row. The number after each cell is how many calls of sink are waiting, counting the one that marks it.

scan meets       new island?  sink marks, in call order     islands
(0,0)            yes          (0,0) 1, (0,1) 2, (1,1) 3     1
(0,1) (1,1)      no: marked
(1,3)            yes          (1,3) 1, (2,3) 2, (3,3) 3,    2
                              (3,2) 4
(2,0)            yes          (2,0) 1                       3
(2,3) (3,2) (3,3) no: marked

Figure 3: the scan meets each island’s first cell once, and by then sink has marked the rest of that island, so the count is 3.

Candidate: From (1,1), sink tries (2,1), which is water, so (2,0) isn’t reached. It starts its own island when the scan meets it. In the checkerboard, every land cell is alone, so the count is 5.

Interviewer: Final cost?

Candidate: O(m·n) time: each cell is marked once and looks at four neighbours. O(m·n) memory for the visited array, plus one waiting call per cell on the current path.

Pause and predict. On a 300 × 300 grid of all land, how many calls of sink wait at once at the deepest point?

Interviewer: The grid can be 300 × 300, all land. Does your code handle that?

The Candidate’s answer

Candidate: No. The calls try “down” first, so from (0,0) they walk down column 0, then up column 1, then down column 2, and so on. No call returns before the last cell, so all 90,000 calls wait at once.

Module 7 met the same limit on trees. Node.js keeps one frame for every call that hasn’t returned, and V8 caps the space for them, at 984 KB on this build. In a run of stack-depth.ts in the module folder, numIslandsDfs threw RangeError: Maximum call stack size exceeded on 300 × 300 of land. It threw on a first call, and again after 2,000 calls on small grids. It also threw on a random 300 × 300 grid with 70% land. The largest square of land it handled on a first call had a side of 96, about 9,200 calls deep.

Candidate: So I mark each island with BFS instead, using a queue in an array. I mark a cell when I put it in the queue, so no cell enters twice.

// O(m·n) time, O(m·n) memory: BFS from each unvisited land cell, with one visited set shared by all
// searches, so every cell enters a queue at most once. The queue is an array read with a head index.
function numIslands(grid: string[][]): number {
  const rows = grid.length;
  const cols = grid[0].length;
  const seen = new Uint8Array(rows * cols);
  let islands = 0;
  for (let start = 0; start < rows * cols; start++) {
    if (grid[Math.floor(start / cols)][start % cols] !== "1" || seen[start]) continue;
    islands++;
    seen[start] = 1; // mark when a cell is put in the queue, not when it is taken out
    const queue = [start];
    for (let head = 0; head < queue.length; head++) {
      const cell = queue[head];
      const r = Math.floor(cell / cols);
      const c = cell % cols;
      for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
        if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
        const next = nr * cols + nc;
        if (grid[nr][nc] === "1" && !seen[next]) {
          seen[next] = 1;
          queue.push(next);
        }
      }
    }
  }
  return islands;
}

export { numIslands };

Candidate: head is the index of the next cell to take out, so taking one out costs nothing. Each cell enters a queue once, so it’s still O(m·n) time and memory, and nothing grows the call stack.

In atlimit.ts, numIslands returned 1 on 300 × 300 of land in 7.6 ms. A loop with your own stack (push and pop on an array) in place of the queue also works, because the order doesn’t matter for counting.

Interviewer: Can you use less memory?

The Candidate’s answer

Candidate: If I may change the grid, I write "0" over each land cell when I mark it. Then the grid is the visited array, and only the queue is extra. I’d ask first, because the caller may still need the grid.

This version isn’t in the lab.

Interviewer: Return the size of the largest island instead.

The Candidate’s answer

Candidate: Every cell of an island enters its queue once, so when the BFS for an island ends, queue.length is the island’s size. I keep the largest. The cost doesn’t change.

That’s LeetCode’s 695. Max Area of Island, which this course doesn’t cover. This version isn’t in the lab.

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

  • Joining diagonal cells. A search over eight neighbours makes the checkerboard 101 010 101 one island. It returns 1 instead of 5. Look at the four side neighbours only.
  • Marking a cell when it leaves the queue. The count stays right, but a cell can be pushed by several neighbours before it’s marked. On 30 × 30 of land, that version pushed 1,741 times for 900 cells. Mark a cell when you push it.
  • Recursion on a big island. numIslandsDfs throws RangeError: Maximum call stack size exceeded on 300 × 300 of land. Use BFS, or a loop with your own stack.

Lab folder: module-09/0200-number-of-islands/ in the course repository.

133. Clone Graph

133. Clone Graph is rated Medium. You get one node of a connected, undirected graph; each node has a value and a list of neighbours. Build a deep copy: new nodes with the same values, joined the same way, with no link to any old node. Return the copy of the node you were given.

  • 0 ≤ V ≤ 100 nodes
  • 1 ≤ val ≤ 100, and every value is different
  • no edge from a node to itself, and no repeated edges
  • the graph is connected, and each edge is listed in both nodes’ neighbors

LeetCode’s TypeScript template declares a class _Node with the fields val: number and neighbors: _Node[]. Its constructor takes both, with 0 and [] as defaults. The lab declares it the same way in node.ts, so paste only the functions. The signature is function cloneGraph(node: _Node | null): _Node | null. Try it on LeetCode first.

Hint

When you meet a node for the second time, you must link to the copy you already made. How do you find that copy fast?

Interviewer: Here’s one node of a connected graph. Return a deep copy of the whole graph.

Candidate: So I make new nodes with the same values and the same edges, and no copy may point to an old node. I return the copy of the node you gave me. Can the input be null?

Interviewer: Yes, for a graph with no nodes. Return null then.

Candidate: Do edges go both ways? Can a node be its own neighbour?

Interviewer: Both ways. No node is its own neighbour, and no edge is repeated.

Candidate: Are the values unique?

Interviewer: Yes, from 1 to 100, and there are at most 100 nodes.

Candidate: Here’s my example and three edge cases. I write a graph as the neighbour values of node 1, node 2, and so on.

graph                       expected
[[2,3],[1,3],[1,2,4],[3]]   4 new nodes, joined the same way
null                        null
[[]]                        one new node, no neighbours
[[2],[1]]                   two new nodes, joined: 1 -> 2 -> 1 is a loop

Figure 4 draws the example.

[1] -- [2]          node  neighbours
  \    /            1     2, 3
   [3] -- [4]       2     1, 3
                    3     1, 2, 4
                    4     3

Figure 4: from node 1, the edges lead back to node 1 (1, 2, 3, 1), so a copy must remember which nodes it has already made.

Candidate: The naive answer lists every node first, with a BFS that skips nodes already in the list. Then it makes one copy per node, and links each copy’s neighbours by finding each neighbour’s position in the list.

// O(V·E) time, O(V) memory: lists every original node, copies each, then finds each neighbour's
// copy by scanning the list of originals with indexOf, once per edge end.
export function cloneGraphIndexOf(node: _Node | null): _Node | null {
  if (node === null) return null;
  const originals = [node]; // also the BFS queue, read with a head index
  for (let head = 0; head < originals.length; head++) {
    for (const neighbor of originals[head].neighbors) {
      if (!originals.includes(neighbor)) originals.push(neighbor);
    }
  }
  const copies = originals.map((original) => new _Node(original.val));
  for (let i = 0; i < originals.length; i++) {
    for (const neighbor of originals[i].neighbors) {
      copies[i].neighbors.push(copies[originals.indexOf(neighbor)]);
    }
  }
  return copies[0];
}

Candidate: Copy i stands for original i. Each includes and indexOf scans up to V nodes, once per neighbour entry, and there are 2E entries. So it’s O(V·E) time and O(V) memory.

Candidate: At 100 nodes, E is at most 4,950, so about 2 × 10⁶ steps. That fits.

In atlimit.ts, on 100 nodes with every pair joined, it took 1.4 ms.

Interviewer: It fits. What would you change?

Candidate: Each indexOf answers one question, “which copy belongs to this node?”, by scanning. A Map from each original node to its copy answers it in O(1) on average. The same Map also tells me which nodes I’ve already reached, so I don’t need the list.

A Map compares object keys by identity, so two different nodes are two keys even if their values were equal (ECMAScript, section 24.1).

Candidate: I’ll walk the graph with BFS. I make a node’s copy when the node first enters the queue, so the map is also my visited mark.

// O(V + E) time, O(V) memory: BFS; a node's copy is made when the node is put in the queue, and
// the Map from original to copy is the visited set. The queue is an array read with a head index.
function cloneGraph(node: _Node | null): _Node | null {
  if (node === null) return null;
  const copyOf = new Map<_Node, _Node>([[node, new _Node(node.val)]]);
  const queue = [node];
  for (let head = 0; head < queue.length; head++) {
    const original = queue[head];
    const clone = copyOf.get(original)!;
    for (const neighbor of original.neighbors) {
      if (!copyOf.has(neighbor)) {
        copyOf.set(neighbor, new _Node(neighbor.val));
        queue.push(neighbor);
      }
      clone.neighbors.push(copyOf.get(neighbor)!);
    }
  }
  return copyOf.get(node)!;
}

export { cloneGraph };

Interviewer: Trace your example.

Figure 5 shows each node as it’s taken out of the queue.

take  new copies (queued)  queue after  copy's neighbours
1     2, 3                 2 3          1: 2 3
2     -                    3            2: 1 3
3     4                    4            3: 1 2 4
4     -                    (empty)      4: 3

Figure 5: a node’s copy is made when the node first enters the queue, so every neighbour’s copy exists by the time it’s linked.

Candidate: When I take 2, its neighbours 1 and 3 already have copies, so I only link them. For [[2],[1]], node 2 links back to the copy of 1, which was made first, and the loop ends there.

Interviewer: Final cost?

Candidate: O(V + E) time: each node enters the queue once, and each neighbour entry is read once. O(V) memory for the map and the queue.

In atlimit.ts, on 100 nodes with every pair joined, cloneGraph took 0.7 ms.

Interviewer: Can you write it recursively?

The Candidate’s answer

Candidate: Yes. To copy a node, I return its copy if the map has one. Otherwise I make the copy, put it in the map, and then copy each neighbour.

// O(V + E) time, O(V) memory: recursive DFS; a Map from each original to its copy is both the
// visited set and the way to find a neighbour's copy. Recursion depth is at most V (100 here).
export function cloneGraphDfs(node: _Node | null): _Node | null {
  const copyOf = new Map<_Node, _Node>();

  function copy(original: _Node): _Node {
    const existing = copyOf.get(original);
    if (existing) return existing;
    const clone = new _Node(original.val);
    copyOf.set(original, clone); // before the neighbours, so a cycle finds this copy
    for (const neighbor of original.neighbors) clone.neighbors.push(copy(neighbor));
    return clone;
  }

  return node === null ? null : copy(node);
}

Candidate: The calls go at most 100 deep here. That’s safe.

In a run of stack-depth.ts, cloneGraphDfs handled a path of 7,074 nodes on a first call. It took 0.7 ms in atlimit.ts, the same as BFS. On a much larger graph, a long path would overflow the call stack, and BFS would not.

Interviewer: What if the graph isn’t connected, and you get a list of all its nodes?

The Candidate’s answer

Candidate: I keep one map and start the same BFS from every node in the list that the map doesn’t hold yet. It’s still O(V + E).

This version isn’t in the lab.

Interviewer: And if the edges were directed?

The Candidate’s answer

Candidate: Nothing changes. The code copies each edge as it’s listed, in the direction it’s listed.

Two mistakes are common here:

  • Putting the copy in the map after its neighbours. new _Node(original.val, original.neighbors.map(copy)) copies the neighbours before the copy is stored. Node 1 asks for 2, which asks for 1, which has no copy yet, and so on. On two joined nodes, mistakes.ts printed RangeError: Maximum call stack size exceeded. Store the copy first.
  • Reusing the original neighbour list. new _Node(original.val, original.neighbors) makes copies that point back into the old graph. The lab’s tests check that no node reached from the copy is an original. This one isn’t in mistakes.ts.

Lab folder: module-09/0133-clone-graph/ in the course repository.

994. Rotting Oranges

994. Rotting Oranges is rated Medium. Each cell of a grid is empty (0), a fresh orange (1) or a rotten orange (2). Every minute, each fresh orange that shares a side with a rotten one rots. Return the minutes until no fresh orange is left, or -1 if some fresh orange can never rot.

  • 1 ≤ m, n ≤ 10 (at most 100 cells)
  • every cell is 0, 1 or 2

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

Hint

Which oranges can rot something new in minute 3? Only the ones that rotted in minute 2.

Interviewer: Tell me how many minutes it takes for every orange to rot.

Candidate: So each minute, the rot spreads one cell from every rotten orange, and I return the minute the last fresh orange rots. What if there’s no fresh orange at the start?

Interviewer: Then the answer is 0.

Candidate: And fresh oranges with no rotten one anywhere?

Interviewer: Nothing can start the rot, so -1.

Candidate: Does rot spread across corners?

Interviewer: No, only across sides.

Candidate: May I change the grid?

Interviewer: Work on a copy.

Candidate: Here’s my example and three edge cases.

grid                              expected
[[2,1,1,0],[0,1,1,1],[1,1,0,2]]   4      rotten oranges at two corners
[[0]] and [[2]]                   0      nothing fresh to rot
[[1,0,2]]                         -1     the empty cell blocks the rot
[[2,1,1,1,1]]                     4      one minute per orange in a line

Candidate: The naive answer follows the story minute by minute.

The Candidate writes orangesRottingRescan, the function at the top of this page.

Candidate: I collect the oranges to rot before I rot any of them. Otherwise an orange that rotted this minute would rot its neighbour in the same scan.

Candidate: Each minute is a full scan, O(m·n). A line of oranges winding through the grid needs about m·n / 2 minutes, so the worst case is O((m·n)²) time. With the grid full of oranges and the rot in one corner, it’s about m + n minutes. Memory is O(m·n) for the copy.

Candidate: At 10 × 10, the winding line needs 59 minutes, so about 60 scans of 100 cells. That’s 6,000 cell checks, far inside the budget.

So the rescan fits LeetCode’s limit. In atlimit.ts it took 0.4 ms on that winding grid. It’s a fair first answer, and it’s easy to check by hand.

Interviewer: Say the grid is 1,000 × 1,000.

Candidate: Then rot from one corner needs about 2,000 minutes to cross it, and each minute scans 10⁶ cells. That’s 2 × 10⁹ steps, 20 times the budget.

Interviewer: What does each scan repeat?

Candidate: It reads every cell again, including oranges that rotted long ago and cells far from the rot. Only an orange that rotted in the last minute can rot something new. So I keep those in a queue and look only at their neighbours.

Candidate: That’s BFS, started from every rotten orange at once. The queue starts with all the rotten oranges at minute 0, then their fresh neighbours at minute 1, and so on. Each level of the queue is one minute.

A BFS whose queue starts with several nodes at distance 0 is a multi-source BFS. It gives every node its distance to the nearest start. When every step costs the same, BFS reaches nodes in order of their distance (Sedgewick and Wayne, section 4.1), so the minute an orange rots is its distance to the nearest rotten orange.

// O(m·n) time, O(m·n) memory: BFS that starts from every rotten orange at once, one level per minute.
// Each orange enters the queue once. The queue is an array read with a head index.
function orangesRotting(grid: number[][]): number {
  const rows = grid.length;
  const cols = grid[0].length;
  const cells = grid.map((row) => [...row]);
  const queue: number[] = []; // cell numbers r * cols + c
  let fresh = 0;
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (cells[r][c] === 2) queue.push(r * cols + c);
      else if (cells[r][c] === 1) fresh++;
    }
  }
  let minutes = 0;
  let head = 0;
  while (head < queue.length && fresh > 0) {
    const levelEnd = queue.length; // everything before levelEnd rotted by the end of this minute
    for (; head < levelEnd; head++) {
      const r = Math.floor(queue[head] / cols);
      const c = queue[head] % cols;
      for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
        if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || cells[nr][nc] !== 1) continue;
        cells[nr][nc] = 2; // mark when it enters the queue
        fresh--;
        queue.push(nr * cols + nc);
      }
    }
    minutes++;
  }
  return fresh === 0 ? minutes : -1;
}

export { orangesRotting };

Candidate: levelEnd is where this minute’s oranges end in the queue, so oranges pushed during the loop belong to the next minute. The loop also stops when nothing is fresh, so it never counts a minute that rots nothing.

Interviewer: Trace your example.

Figure 6 shows the minute each orange in the example rots.

grid          minute it rots
2 1 1 0       0 1 2 .
0 1 1 1       . 2 2 1
1 1 0 2       4 3 . 0

Figure 6: each orange rots at its distance in steps from the nearer rotten orange, and the largest distance, 4, is the answer.

Figure 7 shows the queue one level at a time, as (r,c).

minute  this level of the queue   fresh left after it
start   (0,0) (2,3)               7
1       (0,1) (1,3)               5
2       (1,1) (0,2) (1,2)         2
3       (2,1)                     1
4       (2,0)                     0    the loop stops: return 4

Figure 7: each level holds only the oranges that rotted in the minute before, so the search never reads a cell far from the rot.

Candidate: For [[2]], fresh starts at 0, so the loop never runs and I return 0. For [[1,0,2]], the queue empties with one orange still fresh, so I return -1.

Interviewer: Final cost?

Candidate: O(m·n) time: each orange enters the queue once and looks at four neighbours. O(m·n) memory for the copy and the queue.

In atlimit.ts, orangesRotting took 0.1 ms on the winding 10 × 10 grid. The measurement at the end of this page compares the two answers on larger grids.

Interviewer: Can you also return the minute each orange rots?

The Candidate’s answer

Candidate: I keep an array of minutes, one per cell, and fill it when a cell enters the queue: one more than the cell that rotted it. That’s Figure 6, and it’s each cell’s distance to the nearest start.

LeetCode’s 542. 01 Matrix asks for the same kind of distance, and this course doesn’t cover it. This version isn’t in the lab.

Interviewer: Why not DFS?

The Candidate’s answer

Candidate: DFS follows one path as deep as it can first. So the first time it reaches an orange may be by a long path, which gives a minute that’s too late. BFS reaches every orange first by its shortest path.

Interviewer: What if some oranges take two minutes to rot?

The Candidate’s answer (stretch)

Candidate: Then the steps no longer cost the same, and BFS can give a wrong minute. That needs Dijkstra’s algorithm with a heap, which DSA Module 8 teaches and this course doesn’t cover.

Two mistakes are common here:

  • Rotting oranges during the scan. An orange rotted this minute then rots its neighbour in the same scan. Our example returns 2 instead of 4. Collect first, then rot.
  • Counting a minute for every level of the queue. The last level rots nothing, so the count is one too many. Our example returns 5 instead of 4, and [[2]] returns 1 instead of 0. Stop when no fresh orange is left.

Lab folder: module-09/0994-rotting-oranges/ in the course repository.

417. Pacific Atlantic Water Flow

417. Pacific Atlantic Water Flow is rated Medium. A grid gives the height of each cell. Water moves from a cell to a side neighbour of the same or lower height. The Pacific lies along the top row and the left column, and the Atlantic along the bottom row and the right column. An edge cell drains into the ocean beside it. Return every cell from which water can reach both oceans.

  • 1 ≤ m, n ≤ 200 (up to 40,000 cells)
  • 0 ≤ heights[r][c] ≤ 10^5

The signature is function pacificAtlantic(heights: number[][]): number[][], returning [row, col] pairs. Try it on LeetCode first.

Hint

Asking where water from each cell can go repeats almost the same search for neighbouring cells. Ask instead which cells each ocean can be reached from.

Interviewer: Find every cell from which water can reach both oceans.

Candidate: So water runs from a cell to a lower neighbour, and I return the cells whose water reaches a Pacific edge and an Atlantic edge. Does it also move between cells of equal height?

Interviewer: Yes. Same or lower.

Candidate: The top-right and the bottom-left corners touch both oceans, then. Does water move across corners?

Interviewer: No, only across sides.

Candidate: How big is the grid, and in what order do you want the cells?

Interviewer: Up to 200 × 200, heights from 0 to 10⁵. Return the cells in row order.

Candidate: Here’s my example and three edge cases.

heights                     expected
[[1,2,3],[8,9,8],[3,2,1]]   [[0,2],[1,0],[1,1],[1,2],[2,0]]  ridge, 2 corners
[[1]]                       [[0,0]]          one cell touches both oceans
a flat grid                 every cell       water moves between equal heights
[[1,1,1],[1,0,1],[1,1,1]]   the 8 outer cells, not the pit in the middle

Candidate: The naive answer follows the water from every cell: a BFS downhill that stops once it has touched both oceans.

// O((m·n)^2) time, O(m·n) memory: from every cell, a BFS that follows the water downhill and stops
// once it has touched both oceans. Neighbouring cells repeat almost the same search.
export function pacificAtlanticPerCell(heights: number[][]): number[][] {
  const rows = heights.length;
  const cols = heights[0].length;
  const result: number[][] = [];
  for (let start = 0; start < rows * cols; start++) {
    const seen = new Uint8Array(rows * cols);
    seen[start] = 1;
    const queue = [start];
    let pacific = false;
    let atlantic = false;
    for (let head = 0; head < queue.length && !(pacific && atlantic); head++) {
      const r = Math.floor(queue[head] / cols);
      const c = queue[head] % cols;
      if (r === 0 || c === 0) pacific = true;
      if (r === rows - 1 || c === cols - 1) atlantic = true;
      for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
        if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
        const next = nr * cols + nc;
        if (!seen[next] && heights[nr][nc] <= heights[r][c]) {
          seen[next] = 1;
          queue.push(next);
        }
      }
    }
    if (pacific && atlantic) result.push([Math.floor(start / cols), start % cols]);
  }
  return result;
}

Candidate: Each search can visit every cell, and there’s one per cell, so it’s O((m·n)²) time and O(m·n) memory. At 200 × 200, that’s 1.6 × 10⁹ steps, 16 times the budget.

atlimit.ts ran it on two 200 × 200 grids. On a bowl, where heights rise toward the edges, no inner cell reaches an ocean, so every search walks every lower cell: 42,617.1 ms. On a flat grid it took 32,322.8 ms. That’s far too slow.

Interviewer: What does it repeat?

Candidate: Neighbouring cells run almost the same search. I’ll turn the question around: which cells can each ocean be reached from? Water flows down, so from the ocean I climb, to neighbours of the same or greater height.

Candidate: One climb starts from every Pacific edge cell, another from every Atlantic edge cell, and a cell that both climbs reach is in the answer. I’ll write the climb as a recursive DFS.

// O(m·n) time, O(m·n) memory: walk uphill from each ocean's edge cells with a recursive DFS; a cell
// counts if both walks reach it. One call stack frame per cell on the current path.
export function pacificAtlanticDfs(heights: number[][]): number[][] {
  const rows = heights.length;
  const cols = heights[0].length;
  const pacific = new Uint8Array(rows * cols);
  const atlantic = new Uint8Array(rows * cols);

  function climb(reached: Uint8Array, r: number, c: number): void {
    reached[r * cols + c] = 1;
    for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
      if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
      if (!reached[nr * cols + nc] && heights[nr][nc] >= heights[r][c]) climb(reached, nr, nc);
    }
  }

  for (let r = 0; r < rows; r++) {
    if (!pacific[r * cols]) climb(pacific, r, 0);
    if (!atlantic[r * cols + cols - 1]) climb(atlantic, r, cols - 1);
  }
  for (let c = 0; c < cols; c++) {
    if (!pacific[c]) climb(pacific, 0, c);
    if (!atlantic[(rows - 1) * cols + c]) climb(atlantic, rows - 1, c);
  }
  const result: number[][] = [];
  for (let cell = 0; cell < rows * cols; cell++) {
    if (pacific[cell] && atlantic[cell]) result.push([Math.floor(cell / cols), cell % cols]);
  }
  return result;
}

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

Interviewer: Trace your example.

Figure 8 shows what each climb reaches. P and A mark a cell the Pacific or the Atlantic climb reached, and * marks the answer.

heights    Pacific climb   Atlantic climb   both
1 2 3      P P P           . . A            . . *
8 9 8      P P P           A A A            * * *
3 2 1      P . .           A A A            * . .

Figure 8: each ocean’s climb marks every cell whose water can run down to that ocean, so the answer is the cells both climbs mark.

Candidate: (0,0) has height 1, and both its neighbours are higher, so water from it reaches only the Pacific. The Atlantic climb stops at (1,0), because 1 is lower than 8. For a flat grid, each climb reaches every cell, so every cell is in the answer.

Interviewer: Final cost?

Candidate: O(m·n) time: each climb marks a cell at most once and looks at four neighbours. O(m·n) memory for the two arrays, plus one waiting call per cell on the current path.

Interviewer: On a flat 200 × 200 grid, how deep do your calls go?

The Candidate’s answer

Candidate: As deep as in 200: the calls snake through all 40,000 cells before one returns. That’s too deep.

In a run of stack-depth.ts, pacificAtlanticDfs threw RangeError: Maximum call stack size exceeded on a flat 200 × 200 grid, on a first call and after a warm-up. The largest flat square it handled on a first call had a side of 61, about 3,700 calls. That’s fewer than 200’s 9,200, because V8 limits the stack in bytes, and a climb call takes more of them than a sink call. DSA Module 6 measured how frames with more arguments and locals fit fewer calls.

Candidate: So each climb is a multi-source BFS, like 994, with every edge cell of one ocean in the queue at the start.

// O(m·n) time, O(m·n) memory: two BFS walks uphill, each starting from all of one ocean's edge cells
// at once; every cell enters each walk's queue at most once. The queue is an array read with a head index.
function pacificAtlantic(heights: number[][]): number[][] {
  const rows = heights.length;
  const cols = heights[0].length;

  function climbFrom(edge: number[]): Uint8Array {
    const reached = new Uint8Array(rows * cols);
    const queue: number[] = [];
    for (const cell of edge) {
      if (!reached[cell]) {
        reached[cell] = 1;
        queue.push(cell);
      }
    }
    for (let head = 0; head < queue.length; head++) {
      const r = Math.floor(queue[head] / cols);
      const c = queue[head] % cols;
      for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
        if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
        const next = nr * cols + nc;
        if (!reached[next] && heights[nr][nc] >= heights[r][c]) {
          reached[next] = 1;
          queue.push(next);
        }
      }
    }
    return reached;
  }

  const pacificEdge: number[] = [];
  const atlanticEdge: number[] = [];
  for (let r = 0; r < rows; r++) {
    pacificEdge.push(r * cols);
    atlanticEdge.push(r * cols + cols - 1);
  }
  for (let c = 0; c < cols; c++) {
    pacificEdge.push(c);
    atlanticEdge.push((rows - 1) * cols + c);
  }
  const pacific = climbFrom(pacificEdge);
  const atlantic = climbFrom(atlanticEdge);
  const result: number[][] = [];
  for (let cell = 0; cell < rows * cols; cell++) {
    if (pacific[cell] && atlantic[cell]) result.push([Math.floor(cell / cols), cell % cols]);
  }
  return result;
}

export { pacificAtlantic };

Candidate: A corner sits in two edge lists, so climbFrom checks reached before it queues an edge cell. The cost stays O(m·n) time and memory, with no recursion.

In atlimit.ts, pacificAtlantic took 1.9 ms on the bowl and 5.7 ms on the flat grid, against 42,617.1 ms and 32,322.8 ms for the search from every cell.

Interviewer: Which cells reach exactly one ocean?

The Candidate’s answer

Candidate: I keep both arrays and report the cells that one climb marked and the other didn’t. The cost doesn’t change.

This version isn’t in the lab.

Interviewer: And with a different ocean on each of the four sides?

The Candidate’s answer

Candidate: One climb per ocean, from its own edge, and a cell counts if all four reach it. With k oceans, that’s O(k · m · n).

This version isn’t in the lab.

Two mistakes are common here:

  • Climbing only to higher cells. Water also moves between equal heights. On the plateau [[1,1,1],[1,5,5],[1,5,5],[1,1,1]], a climb with > returns 4 cells instead of all 12. Climb with >=.
  • Recursion on a flat grid. pacificAtlanticDfs throws RangeError: Maximum call stack size exceeded on a flat 200 × 200 grid. Use BFS.

Lab folder: module-09/0417-pacific-atlantic-water-flow/ in the course repository.

207. Course Schedule

207. Course Schedule is rated Medium. Courses are numbered from 0 to numCourses − 1. A pair [a, b] means you must take course b before course a. Return whether you can take every course.

  • 1 ≤ numCourses ≤ 2000
  • 0 ≤ prerequisites.length ≤ 5000
  • each pair is [a, b] with 0 ≤ a, b < numCourses
  • no pair appears twice

The signature is function canFinish(numCourses: number, prerequisites: number[][]): boolean. Try it on LeetCode first.

Hint

Which courses can you take on the first day? What changes for the other courses when you take one?

Interviewer: Here are the courses and their prerequisites. Can a student take every course?

Candidate: So a pair [a, b] means b first, then a. The answer is no when some courses wait for each other in a loop. Can a course need itself?

Interviewer: The limits don’t rule it out.

Candidate: Then that course can never be taken, and I return false. Can a course have no pairs at all?

Interviewer: Yes. It can be taken any time.

Candidate: Can the courses fall into separate groups, with no pairs between them?

Interviewer: Yes.

With an edge from b to a for each pair, the courses form a directed graph. A cycle is a path that comes back to its start, as in Module 6‘s lists. A directed graph with no cycle is a directed acyclic graph, or DAG, and every course can be taken exactly when the graph is a DAG.

Candidate: Here’s my example and three edge cases.

numCourses  prerequisites                expected
4           [[1,0],[2,0],[3,1],[3,2]]    true   0, then 1 and 2, then 3
1           [[0,0]]                      false  a course that needs itself
4           [[1,0],[3,2],[2,3]]          false  the cycle 2, 3 avoids course 0
3           []                           true   no pairs

Figure 9 draws the example, with the lists the code below keeps for each course.

       [0]             course  needs   unlocks  waits for
      /   \            0       -       1, 2     0
   [1]     [2]         1       0       3        1
      \   /            2       0       3        1
       [3]             3       1, 2    -        2

Figure 9: the edges point down, from a course to the courses it unlocks, and only course 0 waits for nothing at the start.

needs[course] lists the courses it needs. A list of neighbours for each node is an adjacency list, and it takes O(V + E) memory.

Candidate: The naive answer takes courses the way a student would. I pass over every course and take each one whose prerequisites are all taken. I repeat until a pass takes nothing.

// O(V·(V + E)) time, O(V + E) memory: pass over every course again and again, taking each course whose
// prerequisites are all taken, until a pass takes nothing. A chain listed backwards needs V passes.
export function canFinishRescan(numCourses: number, prerequisites: number[][]): boolean {
  const needs: number[][] = Array.from({ length: numCourses }, () => []);
  for (const [course, before] of prerequisites) needs[course].push(before);
  const taken = new Uint8Array(numCourses);
  let takenCount = 0;
  let progress = true;
  while (progress) {
    progress = false;
    for (let course = 0; course < numCourses; course++) {
      if (!taken[course] && needs[course].every((before) => taken[before])) {
        taken[course] = 1;
        takenCount++;
        progress = true;
      }
    }
  }
  return takenCount === numCourses;
}

Candidate: A course on a cycle waits for another course on the same cycle, so it’s never taken. Every other course is taken at some point.

Candidate: A pass reads every course and every pair, O(V + E). In the worst order, a chain where course i needs course i + 1, each pass takes one course, so there are V passes: O(V·(V + E)) time. Memory is O(V + E) for the lists.

Candidate: At the limit that’s 2,000 × 7,000, about 1.4 × 10⁷ steps. That fits.

In atlimit.ts it took 17.8 ms on 2,000 courses: a chain listed backwards, plus random pairs up to 5,000. So the rescan passes here.

Interviewer: It passes. What does each pass do again?

Candidate: It rereads every course to find the few that became ready. But a course only becomes ready when one of its prerequisites is taken. So I keep, for each course, how many prerequisites it still waits for. When I take a course, I lower the count of every course it unlocks, and a course that reaches 0 goes into a queue.

The number of edges that lead into a node is its in-degree. Here it’s the number of prerequisites a course waits for. Taking courses from a queue of in-degree 0 is Kahn’s algorithm, after A. B. Kahn, who published it in 1962 (doi:10.1145/368996.369025).

The order in which courses leave the queue is a topological order: an order where b comes before a for every pair. A directed graph has one exactly when it’s a DAG (Sedgewick and Wayne, section 4.2).

// O(V + E) time, O(V + E) memory: Kahn's algorithm. Count each course's untaken prerequisites; queue the
// courses at zero; taking one lowers the count of every course that needs it. Each course enters the
// queue once and each pair is read twice. The queue is an array read with a head index.
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
  const unlocks: number[][] = Array.from({ length: numCourses }, () => []);
  const waitingFor = new Int32Array(numCourses);
  for (const [course, before] of prerequisites) {
    unlocks[before].push(course);
    waitingFor[course]++;
  }
  const queue: number[] = [];
  for (let course = 0; course < numCourses; course++) {
    if (waitingFor[course] === 0) queue.push(course);
  }
  for (let head = 0; head < queue.length; head++) {
    for (const next of unlocks[queue[head]]) {
      waitingFor[next]--;
      if (waitingFor[next] === 0) queue.push(next);
    }
  }
  return queue.length === numCourses; // courses on a cycle never reach zero
}

export { canFinish };

Candidate: waitingFor is an Int32Array, a typed array of integers that starts at zeros. A course on a cycle waits for a course on the same cycle, so its count never reaches 0. Every course enters the queue exactly when there’s no cycle.

Interviewer: Trace your example.

Figure 10 shows the counts after each course is taken, for courses 0, 1, 2 and 3.

take   waits for (0 1 2 3)   queue
start  0 1 1 2               0
0      0 0 0 2               0 1 2
1      0 0 0 1               0 1 2
2      0 0 0 0               0 1 2 3
3      0 0 0 0               0 1 2 3
                             4 courses = numCourses: true

Figure 10: taking a course lowers only the counts of the courses it unlocks, so course 3 joins the queue the moment its last prerequisite is taken.

Pause and predict. Add the pair [1, 3], so course 1 also needs course 3. Which courses enter the queue now?

Candidate: Course 1 waits for 0 and 3, and course 3 waits for 1 and 2. Taking 0 frees 2, and taking 2 lowers 3 to 1. Then the queue runs out: it holds 0 and 2, two courses of four, so I return false.

Candidate: For [[0,0]], course 0 waits for itself, so the queue starts empty, and 0 of 1 courses is false.

Interviewer: Final cost?

Candidate: O(V + E) time: each course enters the queue once, and each pair is read twice, once to build the lists and once to unlock. O(V + E) memory for the lists.

In atlimit.ts, canFinish took 1.3 ms on the same input as the rescan.

Interviewer: Can you find a cycle with DFS instead?

The Candidate’s answer

Candidate: Yes. Each course is new, on the current path, or done. From each new course, I visit what it needs. Meeting a course that’s on the current path means a cycle; meeting a done course is fine. A course is done when everything it needs is done.

// O(V + E) time, O(V + E) memory: recursive DFS with three states. Meeting a course that is still on
// the current path means a cycle. Recursion depth is the longest chain of prerequisites, up to V.
export function canFinishDfs(numCourses: number, prerequisites: number[][]): boolean {
  const needs: number[][] = Array.from({ length: numCourses }, () => []);
  for (const [course, before] of prerequisites) needs[course].push(before);
  const NEW = 0, ON_PATH = 1, DONE = 2;
  const state = new Uint8Array(numCourses); // all NEW

  function hasCycleFrom(course: number): boolean {
    state[course] = ON_PATH;
    for (const before of needs[course]) {
      if (state[before] === ON_PATH) return true;
      if (state[before] === NEW && hasCycleFrom(before)) return true;
    }
    state[course] = DONE;
    return false;
  }

  for (let course = 0; course < numCourses; course++) {
    if (state[course] === NEW && hasCycleFrom(course)) return false;
  }
  return true;
}

Candidate: It’s O(V + E) time and memory. The calls go as deep as the longest chain of prerequisites, at most 2,000 here.

In a run of stack-depth.ts, canFinishDfs handled a chain of 5,171 courses on a first call, so 2,000 is safe. It took 1.5 ms in atlimit.ts. Unlike 200 and 417, this recursion fits the limits.

Interviewer: Can you return the cycle itself?

The Candidate’s answer

Candidate: I keep the current path in an array as the DFS goes. When I meet a course that’s on the path, the cycle is the part of the path from that course to the end.

DSA Module 7 has this as its exercise find-cycle. This version isn’t in the lab.

Interviewer: A student may take any number of courses per term. How many terms are needed?

The Candidate’s answer

Candidate: I run Kahn’s algorithm one level at a time, as in 994. The courses ready at the start are term 1, the courses they free are term 2, and so on. The number of levels is the answer, with the same cost.

This version isn’t in the lab.

Two mistakes are common here:

  • DFS with only “seen”. If any course seen before counts as a cycle, the example fails: course 0 is reached twice, through 1 and through 2, with no cycle. It returns false instead of true. Keep three states; only a course on the current path means a cycle.
  • Starting only from course 0. A cycle in a group that course 0 can’t reach is missed. [[1,0],[3,2],[2,3]] returns true instead of false. Start from every course. This one isn’t in mistakes.ts.

Lab folder: module-09/0207-course-schedule/ in the course repository.

210. Course Schedule II

210. Course Schedule II is rated Medium. The courses and pairs are the same as in 207. Return an order that takes every course with each prerequisite first, or an empty array if there’s none. Any valid order is accepted.

  • 1 ≤ numCourses ≤ 2000
  • 0 ≤ prerequisites.length ≤ numCourses × (numCourses − 1)
  • each pair is [a, b] with 0 ≤ a, b < numCourses and a ≠ b
  • no pair appears twice

The signature is function findOrder(numCourses: number, prerequisites: number[][]): number[]. Try it on LeetCode first.

Hint

In 207, Kahn’s queue held the courses in the order they could be taken.

Interviewer: Same courses. Now give me an order that takes them all, or an empty array if there’s none.

Candidate: So it’s 207, but I return the order itself. Any valid order?

Interviewer: Yes, any.

Candidate: And [a, b] still means b first?

Interviewer: Yes. A course never needs itself here.

Candidate: How many pairs can there be?

Interviewer: Up to numCourses × (numCourses − 1), so about 4 × 10⁶ at 2,000 courses.

Candidate: Then my answer must be linear in the number of pairs. Here’s my example and three edge cases.

numCourses  prerequisites                    expected (any valid order)
5           [[1,0],[2,0],[3,1],[3,2],[4,2]]  [0,1,2,3,4], [0,2,1,4,3], ...
3           []                               [0,1,2], in any order
5           [[1,0],[2,1],[3,2],[4,3]]        [0,1,2,3,4], the only order
4           [[1,0],[2,1],[3,2],[1,3]]        []   1, 2, 3 form a cycle

Candidate: The naive answer is 207’s rescan, adding each course to the order when it’s taken.

// O(V·(V + E)) time, O(V + E) memory: pass over every course again and again, taking each course whose
// prerequisites are all taken, until a pass takes nothing. A chain listed backwards needs V passes.
export function findOrderRescan(numCourses: number, prerequisites: number[][]): number[] {
  const needs: number[][] = Array.from({ length: numCourses }, () => []);
  for (const [course, before] of prerequisites) needs[course].push(before);
  const taken = new Uint8Array(numCourses);
  const order: number[] = [];
  let progress = true;
  while (progress) {
    progress = false;
    for (let course = 0; course < numCourses; course++) {
      if (!taken[course] && needs[course].every((before) => taken[before])) {
        taken[course] = 1;
        order.push(course);
        progress = true;
      }
    }
  }
  return order.length === numCourses ? order : [];
}

Candidate: It’s O(V·(V + E)) time, as in 207. But E can be about 2 × 10⁶ now, so at 2,000 passes that’s up to 4 × 10⁹ steps, 40 times the budget.

atlimit.ts ran it on 2,000 courses where course i needs every course after it, 1,999,000 pairs. The pairs are listed so that each pass rereads the courses already taken. It took 1,056.8 ms, far more than the faster answers below.

Interviewer: What would you change?

Candidate: The same as in 207: count what each course waits for, and queue the courses at 0. The queue already lists the courses in an order they can be taken, so the queue is my answer.

// O(V + E) time, O(V + E) memory: Kahn's algorithm. The queue of courses whose prerequisites are all
// taken is the answer itself: an array read with a head index, in the order courses entered it.
function findOrder(numCourses: number, prerequisites: number[][]): number[] {
  const unlocks: number[][] = Array.from({ length: numCourses }, () => []);
  const waitingFor = new Int32Array(numCourses);
  for (const [course, before] of prerequisites) {
    unlocks[before].push(course);
    waitingFor[course]++;
  }
  const order: number[] = [];
  for (let course = 0; course < numCourses; course++) {
    if (waitingFor[course] === 0) order.push(course);
  }
  for (let head = 0; head < order.length; head++) {
    for (const next of unlocks[order[head]]) {
      waitingFor[next]--;
      if (waitingFor[next] === 0) order.push(next);
    }
  }
  return order.length === numCourses ? order : []; // courses on a cycle never reach zero
}

export { findOrder };

Interviewer: Trace your example.

Figure 11 shows the counts after each course is taken, for courses 0 to 4.

take   waits for (0 1 2 3 4)   order (the queue)
start  0 1 1 2 1               0
0      0 0 0 2 1               0 1 2
1      0 0 0 1 1               0 1 2
2      0 0 0 0 0               0 1 2 3 4
3      0 0 0 0 0               0 1 2 3 4
4      0 0 0 0 0               0 1 2 3 4
                               5 courses: return [0,1,2,3,4]

Figure 11: a course joins the order only when its count reaches 0, after every course it needs, so the queue is a valid order.

Candidate: For the cycle case, only course 0 waits for nothing. Taking it lowers course 1 from 2 to 1, and then the queue runs out with 1 course of 4, so I return [].

Interviewer: Final cost?

Candidate: O(V + E) time and O(V + E) memory, as in 207.

In atlimit.ts, findOrder took 40.0 ms on the 1,999,000 pairs, against 1,056.8 ms for the rescan.

Interviewer: Can you do it with DFS?

The Candidate’s answer

Candidate: Yes, with 207’s three states. I follow each course to what it needs, and add the course to the order when everything it needs is done. Each course comes after its prerequisites, so that’s already a valid order.

A walk that handles a node after everything below it is a post-order walk, as Module 7 defined it. Here the edges point from a course to what it needs, so the post-order needs no reversal.

// O(V + E) time, O(V + E) memory: recursive DFS with three states, following each course to what it
// needs. A course is added after everything it needs, so this postorder is already a valid order.
// Recursion depth is the longest chain of prerequisites, up to V.
export function findOrderDfs(numCourses: number, prerequisites: number[][]): number[] {
  const needs: number[][] = Array.from({ length: numCourses }, () => []);
  for (const [course, before] of prerequisites) needs[course].push(before);
  const NEW = 0, ON_PATH = 1, DONE = 2;
  const state = new Uint8Array(numCourses);
  const order: number[] = [];

  function visit(course: number): boolean { // false if a cycle was found
    state[course] = ON_PATH;
    for (const before of needs[course]) {
      if (state[before] === ON_PATH) return false;
      if (state[before] === NEW && !visit(before)) return false;
    }
    state[course] = DONE;
    order.push(course);
    return true;
  }

  for (let course = 0; course < numCourses; course++) {
    if (state[course] === NEW && !visit(course)) return [];
  }
  return order;
}

Candidate: The depth is at most 2,000, which stack-depth.ts showed is safe, as in 207.

It took 31.7 ms in atlimit.ts. On our example it also returns [0,1,2,3,4], but on other inputs DFS and Kahn’s algorithm can give different valid orders. That’s why the lab’s tests check that an order is valid, not that it equals one answer.

Interviewer: What if I want the smallest valid order, comparing course numbers from the left?

The Candidate’s answer

Candidate: I replace the queue with a min-heap of the ready courses, the Heap from Module 8. Each step takes the smallest ready course. That’s O(V log V + E) time.

This version isn’t in the lab.

Two mistakes are common here:

  • No final length check. With a cycle, Kahn’s queue holds only the courses it could take. [[1,0],[2,1],[3,2],[1,3]] returns [0] instead of []. Compare the length with numCourses.
  • Reading [a, b] as “a before b”. Every edge points the wrong way, so each course comes before its prerequisites. Our example returns [3,4,1,2,0] instead of [0,1,2,3,4]. The edge goes from b to a: unlocks[b].push(a).

Lab folder: module-09/0210-course-schedule-ii/ in the course repository.

127. Word Ladder

127. Word Ladder is rated Hard. Starting from one word, change one letter at a time, so that every word after the first is in a given list, until you reach a target word. Return how many words the shortest such chain holds, counting the first and the last, or 0 if there’s no chain.

  • every word has the same length L, with 1 ≤ L ≤ 10
  • 1 ≤ wordList.length ≤ 5000 (N below)
  • lowercase English letters only
  • beginWord ≠ endWord, and the list has no repeats

The signature is function ladderLength(beginWord: string, endWord: string, wordList: string[]): number. Try it on LeetCode first.

Hint

Each word is a node. To find the words one letter away from a word, you don’t have to look at the whole list. How many words could be one letter away?

Interviewer: Change cold into warm one letter at a time. Every word after the first must be in this list. How long is the shortest chain?

Candidate: So each step changes one letter and must land on a word in the list. Do I count words or changes?

Interviewer: Words, including the first and the last.

Candidate: Must the first word be in the list? And the last?

Interviewer: The first, no. The last, yes. If it isn’t there, there’s no chain, so return 0.

Candidate: Same length for every word, lowercase only?

Interviewer: Yes. Up to 5,000 words of up to 10 letters.

Candidate: Here’s my example and three edge cases.

begin  end   list                              expected
cold   warm  [cord,card,ward,warm,worm,word]   5   cold cord card ward warm
cold   warm  [cord]                            0   warm isn't in the list
a      c     [b,c]                             2   a -> c in one change
cold   warm  [cord,warm]                       0   warm can't be reached

Candidate: Each word is a node, and an edge joins two words that differ in one letter. Every change is one step, so the shortest chain comes from a BFS from cold. Trying every chain with DFS and keeping the shortest can take exponential time.

Candidate: The obvious way to find a word’s neighbours is to compare it with every word in the list.

function differByOne(a: string, b: string): boolean {
  let differences = 0;
  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i] && ++differences > 1) return false;
  }
  return differences === 1;
}

// O(N^2 · L) time, O(N) memory: to find a word's neighbours, compare it with every word in the list.
export function ladderLengthScan(beginWord: string, endWord: string, wordList: string[]): number {
  if (!wordList.includes(endWord)) return 0;
  const used = new Uint8Array(wordList.length);
  const queue = [beginWord];
  let head = 0;
  let length = 1;
  while (head < queue.length) {
    const levelEnd = queue.length;
    length++;
    for (; head < levelEnd; head++) {
      for (let i = 0; i < wordList.length; i++) {
        if (used[i] || !differByOne(queue[head], wordList[i])) continue;
        if (wordList[i] === endWord) return length;
        used[i] = 1; // mark when it enters the queue
        queue.push(wordList[i]);
      }
    }
  }
  return 0;
}

Candidate: length counts the words in a chain that ends at a word this level finds, so it goes up by one per level. Each of up to N words is compared with N words of L letters: O(N² · L) time, O(N) memory.

Candidate: At the limit that’s 5,000² × 10, or 2.5 × 10⁸ letter comparisons, more than twice the budget.

But differByOne stops at the second difference, so most comparisons read only a few letters. atlimit.ts ran it on 5,000 words of 10 letters, where each word has about 12 neighbours and BFS reaches almost all of them. It took 243.1 ms, so in practice it runs in a quarter of a second, though on paper it’s over the budget.

Interviewer: Can you find a word’s neighbours without reading the whole list?

Candidate: A word of L letters has only 25 × L possible words one letter away. I try all 26 letters at each place and ask a Set of the unused words whether the result is in it. That’s 26 × L lookups per word, however long the list is.

// O(N · L^2 · 26) time, O(N · L) memory: for each word, try all 26 letters at each of its L places and
// look the result up in a Set of the unused words; building one candidate string costs O(L).
function ladderLength(beginWord: string, endWord: string, wordList: string[]): number {
  const unused = new Set(wordList);
  if (!unused.has(endWord)) return 0;
  unused.delete(beginWord); // the first word is used already, even if the list holds it
  const queue = [beginWord];
  let head = 0;
  let length = 1;
  while (head < queue.length) {
    const levelEnd = queue.length;
    length++;
    for (; head < levelEnd; head++) {
      const word = queue[head];
      for (let i = 0; i < word.length; i++) {
        for (let code = 97; code <= 122; code++) { // "a" to "z"
          const candidate = word.slice(0, i) + String.fromCharCode(code) + word.slice(i + 1);
          if (!unused.has(candidate)) continue;
          if (candidate === endWord) return length;
          unused.delete(candidate); // mark when it enters the queue
          queue.push(candidate);
        }
      }
    }
  }
  return 0;
}

export { ladderLength };

Candidate: Deleting a word from the set marks it as used, so it can’t enter the queue twice. I delete beginWord too, in case the list holds it.

Interviewer: Trace your example.

Figure 12 shows each level of the BFS, and the words each level finds. A word is found when a changed letter gives a word that’s still in the set.

length  this level   found (and deleted from the set)
2       cold         cold -> cord
3       cord         cord -> word, cord -> card
4       word card    word -> ward, word -> worm; card finds nothing new
5       ward worm    ward -> warm: the end word, return 5

Figure 12: each level holds the words one more change from cold, so the end word is found at the shortest length, 5.

Candidate: The chain found is cold, cord, word, ward, warm. Mine went through card, and it has the same length, so either is fine. For [cord, warm], the level after cord finds nothing, the queue runs out, and I return 0.

Interviewer: Final cost?

Candidate: Each word enters the queue once and builds 26 × L candidates of L letters: O(N · 26 · L²) time. O(N · L) memory for the set and the queue. At the limit that’s about 1.3 × 10⁷ character steps.

In atlimit.ts, on the same 5,000 words, ladderLength took 84.4 ms, against 243.1 ms for the scan. That’s about three times faster at this limit, not more, because every candidate builds a new string while the scan’s comparisons stop early. The real difference is growth: the scan is quadratic in N, and the set version is linear.

Interviewer: Return every shortest chain, not only the length.

The Candidate’s answer

Candidate: During the BFS, I record for each word the words on the previous level that reach it. When the level that finds the end word is done, I walk back from the end word through those records to list every chain.

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

Interviewer: Can you visit fewer words?

The Candidate’s answer (stretch)

Candidate: I’d search from both ends at once, a bidirectional BFS. Each step grows the smaller of the two searches by one level, and I stop when a word found by one search is in the other. Each search only has to go about half the distance, so both stay smaller. The worst case is the same.

This version isn’t in the lab.

Interviewer: What if I ask many questions about the same list?

The Candidate’s answer

Candidate: I build a Map once, from each pattern with one letter hidden, such as c*ld, to the words that match it. Two words are neighbours exactly when they share a pattern. Building it is O(N · L²), and each question is then a BFS over it.

This version isn’t in the lab.

Two mistakes are common here:

  • Counting changes instead of words. Starting length at 0 returns 4 instead of 5 for cold to warm. The first word counts as 1.
  • Marking a word when it leaves the queue. The answer stays right, but a word can be queued once by each neighbour on the same level, as in 200. Delete it from the set when you push it. This one isn’t in mistakes.ts.

Lab folder: module-09/0127-word-ladder/ in the course repository.

Measured: Rotting Oranges, rescan against BFS

Rotting Oranges, the problem at the top of this page, is the one this module measures, with bench.ts from DSA Module 1. LeetCode’s own limit, 10 × 10, is too small to time, so the grids here go far past it.

// Module 9's measurement: 994. Rotting Oranges, rescanning the grid every minute against BFS.
// Input: a side x side grid, each cell fresh with probability 0.9 and empty otherwise (Math.random()
// per cell), with one rotten orange in the top-left corner. The rot needs about 2 · side minutes to
// cross the grid, so the rescan does about 2 · side scans of side² cells: O(side³); BFS is O(side²).
// Run from the repository root: node module-09/measure.ts
import { bench } from "../shared/bench.ts";
import { orangesRottingRescan, orangesRotting } from "./0994-rotting-oranges/solution.ts";

let sink = 0;

function makeGrid(side: number): number[][] {
  const grid = Array.from({ length: side }, () => Array.from({ length: side }, () => (Math.random() < 0.9 ? 1 : 0)));
  grid[0][0] = 2;
  return grid;
}

// The answer is often -1 (an orange walled in by empty cells); both solutions still spread the rot
// through every orange it can reach before they stop. This line checks that they agree.
const sample = makeGrid(200);
console.log(`one 200 x 200 grid: rescan ${orangesRottingRescan(sample)}, BFS ${orangesRotting(sample)}`);

bench("orangesRottingRescan (side)", [100, 200, 400], makeGrid, (grid) => {
  sink += orangesRottingRescan(grid);
});
bench("orangesRotting, BFS (side)", [100, 200, 400], makeGrid, (grid) => {
  sink += orangesRotting(grid);
});
bench("orangesRotting, BFS, larger (side)", [400, 800, 1600], makeGrid, (grid) => {
  sink += orangesRotting(grid);
});

console.log(`\nsink ${sink}`);

bench runs each size once to warm up, then five times on fresh grids, and prints the median and how many times slower each size is than the one before. The n column is the side of the grid. Making the grids isn’t timed.

Most of these random grids hold an orange that empty cells wall in, so the answer is usually -1. That’s fine for timing: both solutions still spread the rot to every orange it can reach before they stop, and the first line checks that they agree.

Pause and predict. When the side of the grid doubles, by how much should each version’s time grow? The grid has four times the cells, and the rot needs twice the minutes to cross it.

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

one 200 x 200 grid: rescan -1, BFS -1

orangesRottingRescan (side)
             n   median ms   x prev
           100       11.50         
           200       94.78      8.2
           400      744.69      7.9

orangesRotting, BFS (side)
             n   median ms   x prev
           100        0.96         
           200        5.46      5.7
           400        8.51      1.6

orangesRotting, BFS, larger (side)
             n   median ms   x prev
           400        7.86         
           800       31.95      4.1
         1,600      133.26      4.2

sink 1140

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.

The rescan grew 8.2 and 7.9 times per doubling of the side. That’s the 8 times of O(side³): four times the cells in each scan, and twice the scans.

BFS took under 10 ms up to side 400, and at those times its ratios (5.7, then 1.6) jump around too much to read. On the larger grids it grew 4.1 and 4.2 times per doubling, the 4 times of O(side²), one visit per cell. At side 400, 160,000 cells, the rescan took 744.69 ms against 8.51 ms, about 87 times longer.

At LeetCode’s 10 × 10, both took under a millisecond in atlimit.ts. So the rescan is an answer that passes, and BFS is the answer for the interviewer’s larger grid. sink adds up the answers, so V8 can’t skip the calls.

Underneath: graphs, queues and the call stack in JavaScript

JavaScript has no graph type, and none of this module’s solutions needs one. A grid is an implicit graph, and the course problems build adjacency lists as arrays of arrays (number[][]), O(V + E) memory (Sedgewick and Wayne, section 4.1). The visited marks are a Uint8Array, one byte per cell or course. DSA Module 7 measured a grid search that keys its marks by "r,c" strings up to 9 times slower than one with numbered cells. 133 and 127 key a Map or Set by an object or a string instead. The specification requires those to find a key in less than linear time on average (ECMAScript, section 24.1).

Every BFS here reads its queue with a head index. The specification defines Array.prototype.shift as moving every remaining item down one place, which is O(n) per call (ECMAScript, section 23.1.3.27). V8 avoids the move on short arrays, but DSA Module 5 found it copying above roughly 15,000 items. With shift(), the array holds only the cells waiting in a grid’s BFS, and that stays short. So in mistakes.ts, shift() cost nothing extra at 300 × 300 (11.1 ms against 11.3 ms), and 1.5 times more at 1,000 × 1,000 (80.5 ms against 53.4 ms). The head index keeps the cost O(V + E) whatever the engine does. Because each node is marked as it enters, at most V items ever enter, so the array’s memory stays O(V), and the ring buffer Deque from Module 8 isn’t needed.

Recursion is where graphs differ most from Module 7’s trees. V8 limits the call stack by bytes, 984 KB by default on this build (node --v8-options), and DSA Module 6 shows where that default comes from. A recursive search keeps one frame per node on its current path. On a grid, that path can snake through every cell, so 200 and 417 overflow at their limits. The course searches go at most 2,000 deep, and Clone Graph’s at most 100, so their recursion fits.

Cheat sheet

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

sign in the problem          problem  the move                    cost
count regions of a grid      200      BFS from each new cell      O(m·n)
copy linked objects          133      BFS, Map old -> copy        O(V + E)
minutes to spread from many  994      multi-source BFS            O(m·n)
cells that reach both edges  417      BFS from each ocean         O(m·n)
can every course be taken    207      Kahn's algorithm            O(V + E)
an order for prerequisites   210      Kahn's queue is the order   O(V + E)
fewest one-letter changes    127      BFS, generate neighbours    O(N·26·L²)

Figure 13: each problem is a graph once you name its nodes and edges, and marking each node once keeps every search linear in their number.

  • Mark on push: mark a node when it enters the queue, in a Uint8Array or a Map; read the queue with a head index, never shift().
  • Fewest steps: BFS, one level per step (levelEnd = queue.length), with every start in the queue at step 0 when there are several.
  • Turn it around: when every cell asks the same question, search once from the target (the oceans in 417).
  • Prerequisites: count what each course waits for; a queue of courses at 0 gives an order, and a short queue means a cycle.
  • Recursion: a recursive DFS on a grid can go m·n calls deep, so it overflows at 300 × 300 (200) and 200 × 200 (417). The course and clone searches fit.
  • Next: Module 10 works backtracking and tries, starting from Word Search II that runs Word Search once per word.

Sources