Data Structures and Algorithms, Pattern by Pattern / Module 07

Module 7: Graphs

Store a graph as adjacency lists, walk it with a visited set, find the fewest steps breadth first, and order dependencies with a topological sort.

Suppose you need the order in which to build the packages of a project, where every package must be built after the packages it depends on. Here is a function that scans the list for a package whose dependencies are all built, builds it, and starts again from the top. Save it as opening-slow.ts:

// Opening problem: build every package after the packages it depends on. The slow version: node opening-slow.ts
import { bench } from "./bench.ts";
import { makePackages, type Packages } from "./packages.ts";

// Scan the list for a package whose dependencies are all built, build it, and scan again from the top.
// Up to V scans, and each can read every package and dependency: O(V * (V + E)) time, O(V) memory.
export function buildOrderSlow(pkgs: Packages): string[] {
  const order: string[] = [];
  const built = new Set<string>();
  while (order.length < pkgs.size) {
    let found = false;
    for (const [name, deps] of pkgs) {
      if (!built.has(name) && deps.every((d) => built.has(d))) {
        built.add(name);
        order.push(name);
        found = true;
        break;
      }
    }
    if (!found) throw new Error("cycle: no package can be built");
  }
  return order;
}

if (process.argv[1] === import.meta.filename) {
  const project: Packages = new Map([
    ["app", ["ui", "api"]],
    ["ui", ["core"]],
    ["api", ["core", "db"]],
    ["db", []],
    ["core", []],
  ]);
  console.log("build order:", buildOrderSlow(project).join(" "));
  bench("buildOrderSlow", [2_000, 4_000, 8_000], makePackages, buildOrderSlow);
}

In one run, it ordered 8,000 generated packages in about one second, and each doubling of the packages made it about 4 times slower. This module turns the packages into a graph and builds the order with a queue of ready packages, so each package and each dependency is handled once. Then it walks graphs without visiting a node twice, and finds the fewest steps across a grid.

After this module, you can:

  • store a graph as adjacency lists or as a matrix, and say what each one costs
  • walk a graph depth first and breadth first with a visited set, and count its separate groups
  • find the fewest steps between two places when every step costs the same, on a grid or on a graph you don’t store
  • order tasks by their dependencies with a topological sort, and detect a cycle

Packages and their dependencies form a graph

Make a folder for the module, as in Module 1, and copy bench.ts into it unchanged. Copy deque.ts from Module 5 as well, because the breadth-first searches use its Deque:

mkdir module-07 && cd module-07 && echo '{ "type": "module" }' > package.json

Then copy packages.ts from the module’s lab folder. It holds three things:

  • Packages, the type for a list of packages: a Map from each package name to the names it depends on
  • makePackages(n), which builds a test input of n packages
  • isValidOrder(pkgs, order), which checks that an order lists every package once, after all of its dependencies

A graph is a set of nodes and the links between them. Each link is an edge. Here every package is a node, and “app depends on ui” is an edge from app to ui.

In a directed graph, every edge has a direction. app needs ui, but ui doesn’t need app.

How is a graph different from the trees of Module 6? A tree has exactly one path from the root to each node. A graph can reach a node by several paths, or come back to where it started.

Figure 1 draws the small project from the opening. Each arrow points from a package to a package it depends on.

             [app]
            /     \
           v       v
        [ui]       [api]
           \      /     \
            v    v       v
            [core]       [db]

listed newest first: app, ui, api, db, core

Figure 1: core is needed by both ui and api, so a walk that starts at app reaches it by two paths.

makePackages(n) builds larger inputs of the same kind. Package i depends on package i − 1 and on up to two random older packages, so there are about 3n edges. The newest package comes first, so pkg0, the only package with no dependencies, is last in the list.

Measure the slow build order

Pause and predict. buildOrderSlow scans the list once for every package it builds. With 2,000, 4,000 and 8,000 packages, how much longer does each doubling take?

Here is what node opening-slow.ts printed:

build order: db core ui api app

buildOrderSlow
             n   median ms   x prev
         2,000       58.07
         4,000      227.52      3.9
         8,000     1006.50      4.4

Every table in this module comes from one run on an Intel Core i7-9750H laptop (x86_64, 6 cores, macOS) with Node.js 26.13.1. Your numbers will differ, but the ratios should look alike.

The time grew about 4 times per doubling, so the function is quadratic: its time grows with the square of the input size. Graph costs use two sizes. V is the number of nodes, here packages, and E is the number of edges, here dependencies.

The loop builds one package per scan, so it scans V times. One scan reads packages and their dependencies until it finds a ready one, which is O(V + E). So the whole function is O(V · (V + E)) time, and O(V) memory for the built set and the order.

In other words, every scan reads almost every package still waiting, because on this input the ready one is always near the end of the list. That’s about V²/2 package checks in all, 32 million for 8,000 packages.

The waste is in the scan. Building one package can only make the packages that depend on it ready, and the scan doesn’t know which packages those are.

Rule: When a loop searches all of the input again after each small change, find the few items the change can affect, and update only those.

Who needs whom: adjacency lists

An adjacency list stores, for each node, the list of nodes its edges point to. The Packages map is already one, because each package maps to the packages it needs.

Which packages can a newly built package make ready? Only the packages that need it. To find them without a scan, you need the edges turned around, so that each package lists the packages that need it. buildOrderKahn in the next section builds that second adjacency list in one pass over the edges.

Figure 2 shows both lists for the small project, as trace-demo.ts prints them. The last column counts the dependencies each package still waits for.

package   needs      needed by   waiting
app       ui, api    -           2
ui        core       app         1
api       core, db   app         2
db        -          api         0
core      -          ui, api     0

Figure 2: the same five edges stored in both directions, so you can follow a dependency either way in O(1) per edge.

Building the “needed by” lists reads every edge once, so it costs O(V + E) time and memory. Only db and core wait for nothing, so they are the packages that can be built first.

Build what is ready: Kahn’s algorithm

The idea uses the waiting counts from Figure 2. Every package with a count of 0 is ready. Build one, then lower the count of each package that needs it. A count that reaches 0 makes that package ready too.

Save opening-fast.ts:

// The build order with Kahn's algorithm: node opening-fast.ts
import { bench } from "./bench.ts";
import { makePackages, type Packages } from "./packages.ts";
import { buildOrderSlow } from "./opening-slow.ts";

// Count the dependencies each package still waits for. A package at 0 is ready; building it
// lowers the count of every package that depends on it.
// O(V + E) time: each package enters the order once, and each edge is followed once.
// O(V + E) memory for the dependents lists, the counts and the order.
export function buildOrderKahn(pkgs: Packages): string[] {
  const dependents = new Map<string, string[]>(); // the edges turned around: package -> packages that need it
  const waiting = new Map<string, number>(); // dependencies not built yet
  for (const [name, deps] of pkgs) {
    waiting.set(name, deps.length);
    for (const d of deps) {
      if (!pkgs.has(d)) throw new Error(`${name} depends on ${d}, which is not in the list`);
      dependents.getOrInsertComputed(d, () => []).push(name);
    }
  }
  const order: string[] = [];
  for (const [name, count] of waiting) if (count === 0) order.push(name);
  // `order` is also the queue: `head` moves forward instead of shift() (Module 5).
  for (let head = 0; head < order.length; head++) {
    for (const next of dependents.get(order[head]) ?? []) {
      const left = waiting.get(next)! - 1;
      waiting.set(next, left);
      if (left === 0) order.push(next);
    }
  }
  if (order.length < pkgs.size) throw new Error("cycle: some packages can never be built");
  return order;
}

if (process.argv[1] === import.meta.filename) {
  const sizes = [2_000, 4_000, 8_000];
  bench("buildOrderSlow", sizes, makePackages, buildOrderSlow);
  bench("buildOrderKahn", sizes, makePackages, buildOrderKahn);
  bench("buildOrderKahn, larger", [100_000, 200_000, 400_000], makePackages, buildOrderKahn);
}

The first loop builds the “needed by” lists with getOrInsertComputed, which Module 3 explained. It also throws when a dependency is not in the list. Such a package can never be built, and without this check the error would wrongly say “cycle”.

order is both the answer and the queue. A package is pushed when its count reaches 0. Then head moves forward through the packages to build next, as the head index did in Module 5.

Figure 3 traces it on the small project, as trace-demo.ts prints it. The packages in brackets are still in the queue.

take    counts lowered          order, queue part in [ ]
start   -                       [db core]
db      api 2->1                db [core]
core    ui 1->0, api 1->0       db core [ui api]
ui      app 2->1                db core ui [api]
api     app 1->0                db core ui api [app]
app     -                       db core ui api app []

Figure 3: a package is queued only when its last dependency is built, so each package is taken once and each edge lowers one count once.

The result is a topological order, a list of a directed graph’s nodes in which every edge points from a later node to an earlier one. In this map, edges point from a package to its dependencies, so every package comes after everything it needs. This queue method is Kahn’s algorithm, published by A. B. Kahn in 1962.

Each package enters the queue once, and each edge lowers one count once, so buildOrderKahn is O(V + E) time. The lists, counts and order take O(V + E) memory.

node opening-fast.ts runs the slow version again, then Kahn’s algorithm on the same sizes and on larger ones:

buildOrderSlow
             n   median ms   x prev
         2,000       63.29
         4,000      226.74      3.6
         8,000      990.58      4.4

buildOrderKahn
             n   median ms   x prev
         2,000        1.21
         4,000        1.65      1.4
         8,000        4.98      3.0

buildOrderKahn, larger
             n   median ms   x prev
       100,000      152.16
       200,000      427.29      2.8
       400,000     1150.62      2.7

At 8,000 packages, the time went from 990.58 ms to 4.98 ms. Figure 4 draws both.

median ms to order n packages (each # is about 22 ms)

n = 2,000   slow   ###                                             63.29
            Kahn   |                                                1.21
n = 4,000   slow   ##########                                     226.74
            Kahn   |                                                1.65
n = 8,000   slow   #############################################  990.58
            Kahn   |                                                4.98

Figure 4: the slow version grows about 4 times per doubling, while Kahn’s algorithm stays a few milliseconds.

Times under 5 ms are too noisy for their ratios to mean much, so the larger sizes show the growth. There, Kahn’s time grew 2.8 and 2.7 times per doubling, a little more than O(V + E) predicts. “Going deeper” looks at why.

Rule: To order tasks by their dependencies, count what each task waits for, queue the tasks at 0, and lower its dependents’ counts when a task is done.

When nothing is ready: cycles

Suppose api needs auth and auth needs api. Neither count can reach 0, so neither package is ever queued, and neither is anything that needs them.

A cycle in a directed graph is a path that follows the edges and comes back to where it started, as api → auth → api does. A directed acyclic graph (DAG) is a directed graph with no cycle. A directed graph has a topological order only if it is a DAG, as Sedgewick and Wayne, section 4.2 shows.

So Kahn’s algorithm also finds cycles, with no extra work. When the queue runs out, every package not in order waits, directly or through others, for a package on a cycle. That’s why buildOrderKahn ends by checking order.length < pkgs.size. Without that check, it returns a short order with no error, as the common mistakes show.

Rule: If Kahn’s algorithm places fewer nodes than the graph has, the graph has a cycle.

Everything a package needs: a walk with a visited set

A different question: which packages does app need, directly or through other packages? That’s every package a walk from app can reach.

Module 6 walked a tree depth first with an explicit stack. On a tree, the walk reaches each node once. On a graph, it can reach a node by several paths, such as core in Figure 1. A cycle can even bring it back to a package it has already left.

A visited set is the set of nodes a walk has already reached, so it can skip any edge that leads back into it. Save needs.ts:

// Everything a package needs, with and without a visited set: node needs.ts
import type { Packages } from "./packages.ts";

// Every package that `name` needs, directly or through other packages, in the order first reached.
// Depth first with an explicit stack and a visited set: O(V + E) time, O(V) memory.
export function allDeps(pkgs: Packages, name: string): string[] {
  const seen = new Set<string>([name]);
  const stack = [name];
  while (stack.length > 0) {
    const pkg = stack.pop()!;
    for (const d of pkgs.get(pkg) ?? []) {
      if (seen.has(d)) continue; // reached before, through another package
      seen.add(d); // mark when pushed, so no package is on the stack twice
      stack.push(d);
    }
  }
  seen.delete(name);
  return [...seen];
}

// The same walk with no visited set. It returns how many times it pushed a package.
export function pushesWithoutSet(pkgs: Packages, name: string): number {
  let pushes = 0;
  const stack = [name];
  while (stack.length > 0) {
    const pkg = stack.pop()!;
    for (const d of pkgs.get(pkg) ?? []) {
      stack.push(d);
      pushes++;
    }
  }
  return pushes;
}

// A ladder of k rungs: a0 and b0 both need a1 and b1, which both need a2 and b2, and so on.
export function ladder(k: number): Packages {
  const pkgs: Packages = new Map();
  for (let i = 0; i <= k; i++) {
    const next = i < k ? [`a${i + 1}`, `b${i + 1}`] : [];
    pkgs.set(`a${i}`, next);
    pkgs.set(`b${i}`, next);
  }
  return pkgs;
}

if (process.argv[1] === import.meta.filename) {
  const project: Packages = new Map([
    ["app", ["ui", "api"]],
    ["ui", ["core"]],
    ["api", ["core", "db"]],
    ["db", []],
    ["core", []],
  ]);
  console.log("allDeps(app):", allDeps(project, "app").join(" "));
  for (const k of [10, 20, 25]) {
    const pkgs = ladder(k);
    let start = performance.now();
    const found = allDeps(pkgs, "a0").length;
    const withSet = performance.now() - start;
    start = performance.now();
    const pushes = pushesWithoutSet(pkgs, "a0");
    const without = performance.now() - start;
    console.log(`ladder of ${k}: ${pkgs.size} packages, a0 needs ${found}; with the set ${withSet.toFixed(2)} ms, without it ${pushes.toLocaleString("en-US")} pushes in ${without.toFixed(0)} ms`);
  }
}

allDeps adds a package to seen when it pushes it, so no package is ever on the stack twice. Figure 5 traces it from app, as trace-demo.ts prints it.

step       stack, top on the right   seen
start      [app]                     app
pop app    [ui api]                  app ui api
pop api    [ui core db]              app ui api core db
pop db     [ui core]                 app ui api core db
pop core   [ui]                      app ui api core db
pop ui     []                        app ui api core db   (core seen: skip)

Figure 5: when ui is popped, its dependency core is already in seen, so the walk skips it and every package is pushed once.

Each package is pushed and popped at most once, and its edges are read once when it is popped. So allDeps is O(V + E) time, and O(V) memory for the set and the stack.

ladder(k) builds a graph where every package on one rung needs both packages on the next rung. So a0 reaches the last rung by 2^k paths, and a walk that doesn’t remember where it has been follows every one of them.

Pause and predict. A ladder of 20 rungs has 42 packages. pushesWithoutSet walks it from a0 with no visited set. How many pushes does it make?

node needs.ts printed:

allDeps(app): ui api core db
ladder of 10: 22 packages, a0 needs 20; with the set 0.04 ms, without it 2,046 pushes in 1 ms
ladder of 20: 42 packages, a0 needs 40; with the set 0.03 ms, without it 2,097,150 pushes in 27 ms
ladder of 25: 52 packages, a0 needs 50; with the set 0.02 ms, without it 67,108,862 pushes in 767 ms

Without the set, a ladder of 20 rungs took 2,097,150 pushes, which is 2^21 − 2, because each rung doubles the number of paths. Five more rungs cost 32 times as much, 767 ms. With the set, the walk pushed each package once and took 0.04 ms or less at every size.

On a graph with a cycle, a walk without a visited set never ends, as the first common mistake shows.

Rule: On a graph, every walk needs a visited set, and a node goes into it when it is first pushed.

Fewest steps: breadth first on a grid

Suppose a warehouse floor is a list of rows, where . is open and # is a shelf. A robot starts in the top-left cell and moves up, down, left or right. How many steps does it need, at the fewest, to reach the bottom-right cell?

The floor is a graph: each open cell is a node, and each open neighbour is an edge. An implicit graph is a graph whose edges you compute when you need them, instead of storing them. Here the edges of a cell are its four neighbours, minus walls and shelves.

Breadth-first search (BFS) from Module 6 visits nodes in order of their distance from the start. With a visited set, it reaches each node first by a path with the fewest edges, as Sedgewick and Wayne, section 4.1 shows. So the step count where BFS first reaches the goal is the answer.

Figure 6 shows the steps BFS assigns to each cell of a small floor, as trace-demo.ts prints it. The floor is on the left, the steps on the right.

...#    0 1 2 #
.#..    1 # 3 4
.#.#    2 # 4 #
....    3 4 5 6

Figure 6: BFS reaches every cell 2 steps away before any cell 3 steps away, so the first number it writes in a cell is the fewest steps to it.

Save grid.ts. It has two versions of the same search, and the next paragraphs explain the difference:

// Fewest steps across a warehouse floor, breadth first: node grid.ts
// The floor is a graph that nobody stores: each open cell is a node, and its open neighbours are its edges.
import { bench } from "./bench.ts";
import { Deque } from "./deque.ts";

export type Grid = string[]; // one string per row: "." open, "#" shelf

// A side x side floor with about 25% shelves. The top row and the right column stay open,
// so there is always a way from the top-left corner to the bottom-right one.
export function makeGrid(side: number): Grid {
  const rows: string[] = [];
  for (let r = 0; r < side; r++) {
    let row = "";
    for (let c = 0; c < side; c++) row += r > 0 && c < side - 1 && Math.random() < 0.25 ? "#" : ".";
    rows.push(row);
  }
  return rows;
}

const MOVES = [[-1, 0], [1, 0], [0, -1], [0, 1]]; // up, down, left, right

// Fewest steps from the top-left cell to the bottom-right cell, or -1 if there is no way.
// Queue items are [row, col, steps], and a Set of "row,col" strings is the visited set.
// O(R * C) time and memory: each cell is queued at most once and has at most four neighbours.
export function fewestStepsStrings(grid: Grid): number {
  const rows = grid.length, cols = grid[0].length;
  if (grid[0][0] === "#") return -1;
  const seen = new Set<string>(["0,0"]);
  const queue = new Deque<[number, number, number]>();
  queue.push([0, 0, 0]);
  while (queue.size > 0) {
    const [r, c, steps] = queue.shift()!;
    if (r === rows - 1 && c === cols - 1) return steps;
    for (const [dr, dc] of MOVES) {
      const nr = r + dr, nc = c + dc;
      if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] === "#") continue;
      const key = `${nr},${nc}`;
      if (seen.has(key)) continue;
      seen.add(key); // mark when queued
      queue.push([nr, nc, steps + 1]);
    }
  }
  return -1;
}

// The same search with numbered cells: cell (r, c) is number r * cols + c. One Int32Array holds
// the steps to each cell, and -1 means "not reached yet", so it is also the visited set.
// O(R * C) time and memory, with no string and no array made per cell.
export function fewestSteps(grid: Grid): number {
  const rows = grid.length, cols = grid[0].length;
  if (grid[0][0] === "#") return -1;
  const dist = new Int32Array(rows * cols).fill(-1);
  const queue = new Deque<number>();
  dist[0] = 0;
  queue.push(0);
  while (queue.size > 0) {
    const cell = queue.shift()!;
    const r = Math.floor(cell / cols), c = cell % cols;
    if (r === rows - 1 && c === cols - 1) return dist[cell];
    for (const [dr, dc] of MOVES) {
      const nr = r + dr, nc = c + dc;
      if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] === "#") continue;
      const next = nr * cols + nc;
      if (dist[next] !== -1) continue;
      dist[next] = dist[cell] + 1; // mark when queued
      queue.push(next);
    }
  }
  return -1;
}

if (process.argv[1] === import.meta.filename) {
  const floor = ["...#", ".#..", ".#.#", "...."];
  console.log("small floor:", fewestStepsStrings(floor), fewestSteps(floor));
  const cells = [250_000, 500_000, 1_000_000]; // sides 500, 707 and 1,000
  const floorOf = (n: number) => makeGrid(Math.round(Math.sqrt(n)));
  bench("fewestStepsStrings (cells)", cells, floorOf, fewestStepsStrings);
  bench("fewestSteps (cells)", cells, floorOf, fewestSteps);
}

fewestStepsStrings is the direct way to write it. Each queue item is [row, col, steps], and the visited set is a Set of "row,col" strings.

fewestSteps numbers the cells, so cell (r, c) becomes r * cols + c. Then one Int32Array, a fixed-length array of 32-bit integers, holds the steps to every cell. A value of -1 means “not reached yet”, so the same array is the visited set.

Both versions mark a cell when they queue it. Each open cell is queued at most once and has at most four neighbours, so both are O(R · C) time and memory for R rows and C columns. In graph terms, V is R · C and E is at most 4V, so that’s O(V + E).

Pause and predict. Both versions have the same Big O. makeGrid builds floors of 250,000 to 1,000,000 cells. How far apart are their times?

node grid.ts printed, with sizes in cells:

small floor: 6 6

fewestStepsStrings (cells)
             n   median ms   x prev
       250,000      144.93
       500,000      299.37      2.1
     1,000,000      714.51      2.4

fewestSteps (cells)
             n   median ms   x prev
       250,000       18.81
       500,000       34.05      1.8
     1,000,000       78.60      2.3

Both grew about 2 times per doubling of the cells, with some extra at 1,000,000. But the numbered version was 9 times faster, 78.60 ms against 714.51 ms.

Why, when the Big O is the same? For every neighbour, fewestStepsStrings builds a new string such as "12,7", and Set.has must compute that string’s hash before it can look in a bucket, as in Module 3. Every queued cell is also a new three-item array. fewestSteps does one multiplication per neighbour and reads one slot of a typed array.

The cost of numbering is code you must get right, such as the r * cols + c arithmetic or a table from names to numbers and back. It pays off on large graphs, or on graphs your code searches often. For a few thousand nodes, the direct version is easier to read and fast enough.

When steps cost different amounts, such as roads of different lengths, BFS no longer gives the shortest path. Module 8 teaches Dijkstra’s algorithm for that, with a heap.

Rule: For the fewest steps when every step costs the same, search breadth first with a queue, and mark each node when you queue it.

Two more shapes of a graph search

The searches above come in two more shapes, each with a sign in the problem that points to it. Save variations.ts:

// Two more shapes of a graph search: node variations.ts
import { Deque } from "./deque.ts";
import { makePackages, type Packages } from "./packages.ts";

// How many separate groups do servers 0 to n - 1 form, given two-way links between them?
// Breadth first from every server not seen yet; each walk finds one whole group.
// O(V + E) time and memory.
export function countGroups(n: number, links: [number, number][]): number {
  const neighbours: number[][] = Array.from({ length: n }, () => []);
  for (const [a, b] of links) {
    neighbours[a].push(b);
    neighbours[b].push(a); // a two-way link is an edge in each direction
  }
  const seen = new Uint8Array(n);
  const queue = new Deque<number>();
  let groups = 0;
  for (let start = 0; start < n; start++) {
    if (seen[start]) continue;
    groups++; // a new group: walk all of it
    seen[start] = 1;
    queue.push(start);
    while (queue.size > 0) {
      for (const next of neighbours[queue.shift()!]) {
        if (seen[next]) continue;
        seen[next] = 1;
        queue.push(next);
      }
    }
  }
  return groups;
}

// The build order depth first: a package goes into the order after all of its dependencies.
// Each package is "path" while the walk is inside it, then "done". Reaching a package that is
// still on the path means the path has come back to it: a cycle.
// O(V + E) time, O(V) memory, but the recursion is as deep as the longest chain of dependencies.
export function buildOrderDfs(pkgs: Packages): string[] {
  const state = new Map<string, "path" | "done">();
  const order: string[] = [];
  function visit(name: string): void {
    const s = state.get(name);
    if (s === "done") return;
    if (s === "path") throw new Error(`cycle through ${name}`);
    state.set(name, "path");
    for (const d of pkgs.get(name)!) {
      if (!pkgs.has(d)) throw new Error(`${name} depends on ${d}, which is not in the list`);
      visit(d);
    }
    state.set(name, "done");
    order.push(name);
  }
  for (const name of pkgs.keys()) visit(name);
  return order;
}

if (process.argv[1] === import.meta.filename) {
  console.log("countGroups:", countGroups(7, [[0, 1], [1, 2], [2, 0], [3, 4], [5, 5]]));
  const project: Packages = new Map([
    ["app", ["ui", "api"]],
    ["ui", ["core"]],
    ["api", ["core", "db"]],
    ["db", []],
    ["core", []],
  ]);
  console.log("buildOrderDfs:", buildOrderDfs(project).join(" "));
  try {
    buildOrderDfs(new Map([["app", ["api"]], ["api", ["auth"]], ["auth", ["api"]]]));
  } catch (err) {
    console.log("with a cycle:", (err as Error).message);
  }
  try {
    buildOrderDfs(makePackages(20_000));
  } catch (err) {
    console.log("20,000 packages:", `${(err as Error).name}: ${(err as Error).message}`);
  }
}

node variations.ts printed:

countGroups: 4
buildOrderDfs: core ui db api app
with a cycle: cycle through api
20,000 packages: RangeError: Maximum call stack size exceeded

Separate groups

Suppose servers are linked by network links, and a link works in both directions. An undirected graph is a graph whose edges have no direction. countGroups stores each link twice, once in each server’s list, so a walk can cross it either way.

A connected component is a largest group of nodes in which each node can reach every other one. Figure 7 draws the demo’s seven servers and links. A line is a two-way link.

group 1           group 2       group 3          group 4

 [0] - [1]        [3] - [4]     [5]              [6]
   \   /                        (link to itself)
    [2]

Figure 7: a walk from any server reaches exactly its own group, so the number of walks started is the number of groups.

countGroups starts a breadth-first walk from every server that no earlier walk reached, and each walk marks a whole group. It printed 4. Every server is queued once and every link is read twice, so it is O(V + E) time and memory.

The sign is “how many separate groups”, or “can a reach b” asked many times on a graph that doesn’t change.

Build order depth first, and finding a cycle

Module 6 named the post-order walk, which handles a node’s children before the node itself. Here, if each package goes into the order after all of its dependencies, the order is a valid build order. That’s buildOrderDfs.

On a graph, a visited set is not enough to find a cycle, because a package can be reached twice without a cycle, as core is. So each package has three states: not seen, “path” while the walk is inside it, and “done” after all its dependencies are. Reaching a package that is still “path” means the walk has come back to it.

Figure 8 traces buildOrderDfs on the small project, as trace-demo.ts prints it. The path column is the recursion’s call stack.

step            path, bottom on the left   order
visit app       app                        -
visit ui        app > ui                   -
visit core      app > ui > core            -
core done       app > ui                   core
ui done         app                        core, ui
visit api       app > api                  core, ui
core is done    app > api                  core, ui
visit db        app > api > db             core, ui
db done         app > api                  core, ui, db
api done        app                        core, ui, db, api
app done        (empty)                    core, ui, db, api, app

Figure 8: core is reached a second time from api while it is “done”, not “path”, so the walk skips it and finds no cycle.

Every package is visited once and every edge followed once, so buildOrderDfs is O(V + E) time and O(V) memory. With api and auth needing each other, it threw cycle through api.

But it recurses once per package on the current path, so a long chain overflows the call stack, as in Module 6. The demo’s 20,000 packages threw RangeError.

So choose by what you need. Kahn’s algorithm has no recursion and finds that a cycle exists. The depth-first walk finds the packages on the cycle, in the order the path reached them. Exercise 4 asks for that cycle with an explicit stack.

Underneath: how to store a graph in JavaScript

Adjacency matrix or adjacency lists

An adjacency matrix is a V × V table where the entry in row a and column b is 1 when there is an edge from a to b. Figure 9 shows the small project as a matrix, as trace-demo.ts prints it.

        app   ui  api   db core
app       0    1    1    0    0
ui        0    0    0    0    1
api       0    0    0    1    1
db        0    0    0    0    0
core      0    0    0    0    0

Figure 9: a matrix has a cell for every pair of nodes, so five edges take 25 cells.

A matrix answers “is there an edge from a to b?” in O(1), while a list must be scanned, which costs O(number of edges leaving a). But a matrix takes O(V²) memory whatever the number of edges. Listing a node’s neighbours reads a whole row, O(V), so a full walk over a matrix is O(V²).

memory.ts in the lab folder builds a graph with about 3 edges per node, once as a Uint8Array matrix (one byte per cell) and once as arrays of neighbours. It runs each size in a fresh Node.js process.

Pause and predict. At 20,000 nodes, how much memory does each take?

V=1000 edges=2997  matrix: 1.0 MB  lists: 0.2 MB  (1000 lists)
V=10000 edges=29997  matrix: 95.4 MB  lists: 1.9 MB  (10000 lists)
V=20000 edges=59997  matrix: 381.5 MB  lists: 3.7 MB  (20000 lists)

At 20,000 nodes, the matrix took 381.5 MB and the lists took 3.7 MB, about 190 bytes per node. Doubling V from 10,000 to 20,000 multiplied the matrix by 4 and the lists by 2, as O(V²) and O(V + E) predict.

Dependency graphs, links between pages and road maps usually have a few edges per node, like this one, so lists win. A matrix pays off when most pairs of nodes have an edge, or when V is small and the code mostly asks whether one edge exists.

What changed recently

Two newer JavaScript features make graph code shorter, and Module 3 explained both:

  • Map.prototype.getOrInsertComputed (ES2026, first in Node.js 26.0.0) builds an adjacency list in one line. On older versions, write let list = m.get(d); if (list === undefined) m.set(d, (list = []));.
  • The Set methods (ES2025), such as difference, give the packages a cycle left out: new Set(pkgs.keys()).difference(new Set(order)). The common mistakes use it.

Both are listed in the TC39 finished proposals. The graph algorithms themselves are decades old.

Common mistakes

mistakes.ts writes five bugs that are easy to make with graphs, and prints what each one returns. Run node mistakes.ts:

1. no visited set: a b c a b c a b c a b c a b c a b c a b
2. pushes on 900 cells, mark on push: 900  mark on pop: 1741
3. order with a cycle: core ui (5 packages)
3. never built: app api auth
3. order with a dependency not in the list: cli (2 packages)
4. groups for links 1-0 and 1-2, one direction only: 2 (want 1)
5. depth first on an open 5 x 5 floor: 16 steps (fewest: 8)

No visited set on a graph with a cycle. The walk goes a b c a b c until the script stops it at 20 steps. Without the cap, it never ends. Keep a visited set on every graph walk.

Marking a node when it is taken out of the queue. The distances stay right, but a cell can be queued once by each neighbour before it is taken out. On an open 30 × 30 floor, the queue took 1,741 pushes for 900 cells. Mark a node when you push it.

Kahn’s algorithm without its checks. With the api and auth cycle, it returned 2 of 5 packages with no error, and difference shows the three it left out. With lib missing from the list, app silently disappeared. Check order.length at the end, and check each dependency’s name.

A two-way link stored in one direction. The links 1–0 and 1–2 connect all three servers. But with each link stored only in its first server’s list, the walk from 0 goes nowhere, and the count is 2. Push each link into both lists.

Depth first for the fewest steps. A depth-first walk reaches the goal by whichever path it tries first. On an open 5 × 5 floor, it reported 16 steps where 8 is the fewest. Use breadth first.

The variations showed the sixth mistake: recursion on a chain whose length comes from input. A dependency chain of 20,000 packages overflowed the call stack.

Exercises

The exercises are in the module’s exercises folder, each with a test file, and the solutions are in solutions. Run all the tests with:

node --test "exercises/*.test.ts"

All 20 tests fail until you write the four answers. Each exercise ends with a test that a correct but naive answer fails. The slow folder holds such answers: the recursive one throws RangeError, and the others fail a time limit.

Exercise 1: are two servers connected? (easy)

Write sameGroup(n, links, pairs), which returns true for each pair [a, b] when server a can reach server b through the two-way links. Start from exercises/same-group.ts:

// Exercise 1: servers 0 to n - 1 and two-way links between them. For each pair [a, b],
// true when a can reach b through the links.
// You may import the Deque from "../deque.ts".
export function sameGroup(n: number, links: [number, number][], pairs: [number, number][]): boolean[] {
  throw new Error("not implemented");
}

The tests check two groups, a server with itself, repeated links and a link to itself, and a chain of 200,000 servers. The last test asks 300 questions on two chains of 100,000 servers in under 300 ms.

Hint

Start from countGroups. What can you store for each server, instead of only counting the groups, so that each question takes O(1)?

Solution
import { Deque } from "../deque.ts";

// Exercise 1: servers 0 to n - 1 and two-way links between them. For each pair [a, b],
// true when a can reach b through the links.
// Breadth first from every server not labelled yet, giving the whole group one number; then each
// question compares two numbers. O(V + E + Q) time for Q questions, O(V + E) memory.
export function sameGroup(n: number, links: [number, number][], pairs: [number, number][]): boolean[] {
  const neighbours: number[][] = Array.from({ length: n }, () => []);
  for (const [a, b] of links) {
    neighbours[a].push(b);
    neighbours[b].push(a);
  }
  const group = new Int32Array(n).fill(-1); // -1: not labelled yet, so also the visited set
  const queue = new Deque<number>();
  let groups = 0;
  for (let start = 0; start < n; start++) {
    if (group[start] !== -1) continue;
    group[start] = groups;
    queue.push(start);
    while (queue.size > 0) {
      for (const next of neighbours[queue.shift()!]) {
        if (group[next] !== -1) continue;
        group[next] = groups;
        queue.push(next);
      }
    }
    groups++;
  }
  return pairs.map(([a, b]) => group[a] === group[b]);
}

Cost: O(V + E + Q) time for Q questions, because the walks queue every server once and read every link twice, and each question compares two numbers. O(V + E) memory for the lists, the labels and the queue. A new search for every question, as in slow/, walks up to a whole group each time, and it took 2,796 ms on the last test.

Exercise 2: the route across the floor (medium)

Write route(grid, start, goal), which returns the cells of a shortest way from start to goal, both included, or null. Start from exercises/route.ts:

// Exercise 2: the cells of a shortest way from `start` to `goal`, both included, moving up, down,
// left or right through open cells ("." open, "#" shelf). null if there is no way.
// You may import the Deque from "../deque.ts".
export function route(grid: string[], start: [number, number], goal: [number, number]): [number, number][] | null {
  throw new Error("not implemented");
}

The tests check two routes around shelves, a start equal to the goal, a goal on a shelf and a walled-in goal. The last test needs an open floor of 700 × 700 in under 300 ms. Any shortest route passes, as long as each step moves one cell onto an open cell.

Hint

Search like fewestSteps. To rebuild the route, use the idea of nearestPath from Module 6, and remember for each cell the cell it was reached from. An Int32Array of cell numbers can hold that.

Solution
import { Deque } from "../deque.ts";

// Exercise 2: the cells of a shortest way from `start` to `goal`, both included, moving up, down,
// left or right through open cells ("." open, "#" shelf). null if there is no way.
// Breadth first on numbered cells, with an Int32Array from each cell to the cell it was reached
// from (-1: not reached yet). O(R * C) time and memory, plus O(L) to rebuild a route of L cells.
export function route(grid: string[], start: [number, number], goal: [number, number]): [number, number][] | null {
  const rows = grid.length, cols = rows > 0 ? grid[0].length : 0;
  const open = (r: number, c: number) => r >= 0 && c >= 0 && r < rows && c < cols && grid[r][c] === ".";
  if (!open(start[0], start[1]) || !open(goal[0], goal[1])) return null;
  const from = new Int32Array(rows * cols).fill(-1);
  const first = start[0] * cols + start[1], last = goal[0] * cols + goal[1];
  from[first] = first; // the start is reached from itself
  const queue = new Deque<number>();
  queue.push(first);
  while (queue.size > 0) {
    const cell = queue.shift()!;
    if (cell === last) {
      const cells: [number, number][] = [];
      for (let x = last; ; x = from[x]) {
        cells.push([Math.floor(x / cols), x % cols]);
        if (x === first) return cells.reverse();
      }
    }
    const r = Math.floor(cell / cols), c = cell % cols;
    for (const [nr, nc] of [[r - 1, c], [r + 1, c], [r, c - 1], [r, c + 1]]) {
      if (!open(nr, nc) || from[nr * cols + nc] !== -1) continue;
      from[nr * cols + nc] = cell; // mark when queued
      queue.push(nr * cols + nc);
    }
  }
  return null;
}

Cost: O(R · C) time and memory, because each cell is queued once. Rebuilding a route of L cells adds O(L). The start points to itself, so the loop that walks back knows where to stop, and -1 still means “not reached”. Carrying a copy of the route in every queue item, as slow/route.ts does, copies up to L cells per step, and it took 1,145 ms on the open floor.

Exercise 3: build stages (medium)

Write buildStages(pkgs), which groups the packages into stages that can build in parallel. The first stage holds the packages with no dependencies, and each later stage holds the packages whose dependencies are all in earlier stages. Start from exercises/build-stages.ts:

// Exercise 3: groups packages into stages that can build in parallel. The first stage holds the
// packages with no dependencies, and each later stage only depends on earlier stages.
// Names inside a stage are sorted. Throws on a cycle or on a dependency that is not in the list.
export function buildStages(pkgs: Map<string, string[]>): string[][] {
  throw new Error("not implemented");
}

Suppose app needs ui and api, ui needs core, api needs core and db, and docs needs nothing. Then the answer is [["core", "db", "docs"], ["api", "ui"], ["app"]]. The tests also check a package that waits for its slowest dependency, an empty map, a cycle, a missing dependency, and a chain of 10,000 packages in under 300 ms.

Hint

Combine buildOrderKahn with the level loop of maxDepthLevels from Module 6. Which packages reach a count of 0 while one stage is being built?

Solution
// Exercise 3: groups packages into stages that can build in parallel. The first stage holds the
// packages with no dependencies, and each later stage only depends on earlier stages.
// Names inside a stage are sorted. Throws on a cycle or on a dependency that is not in the list.
// Kahn's algorithm, one stage at a time: the packages that reach 0 while a stage is built
// form the next stage. O(V log V + E) time (the sort inside each stage), O(V + E) memory.
export function buildStages(pkgs: Map<string, string[]>): string[][] {
  const dependents = new Map<string, string[]>();
  const waiting = new Map<string, number>();
  for (const [name, deps] of pkgs) {
    waiting.set(name, deps.length);
    for (const d of deps) {
      if (!pkgs.has(d)) throw new Error(`${name} depends on ${d}, which is not in the list`);
      dependents.getOrInsertComputed(d, () => []).push(name);
    }
  }
  const stages: string[][] = [];
  let stage = [...pkgs.keys()].filter((name) => waiting.get(name) === 0);
  let placed = 0;
  while (stage.length > 0) {
    stages.push(stage.sort());
    placed += stage.length;
    const next: string[] = [];
    for (const name of stage) {
      for (const d of dependents.get(name) ?? []) {
        const left = waiting.get(d)! - 1;
        waiting.set(d, left);
        if (left === 0) next.push(d);
      }
    }
    stage = next;
  }
  if (placed < pkgs.size) throw new Error("cycle: some packages can never be built");
  return stages;
}

Cost: O(V + E) for the counts and the stages, plus the sort inside each stage, so O(V log V + E) time in the worst case. O(V + E) memory. Scanning every package again for each stage, as slow/build-stages.ts does, is O(V²) on a chain, and it took 2,629 ms on the chain of 10,000.

Exercise 4: find the cycle (harder)

Write findCycle(pkgs), which returns one dependency cycle as a list of names that starts and ends with the same package, or null. It must work on a chain of 100,000 packages. Start from exercises/find-cycle.ts:

// Exercise 4: one dependency cycle as a list of names that starts and ends with the same
// package (["api", "auth", "api"]), or null if there is none.
// It must work on a chain of 100,000 packages.
export function findCycle(pkgs: Map<string, string[]>): string[] | null {
  throw new Error("not implemented");
}

The tests check a graph with no cycle, a diamond (two paths to one package, no cycle), two packages that need each other, and a package that needs itself. Two more check a cycle reached after a shared dependency, and a chain of 100,000 packages without and then with a cycle. Any valid cycle passes.

Hint

Use the three states of buildOrderDfs, but keep the current path in an array instead of the call stack. A second array next to it holds, for each package on the path, the index of its next dependency to try. These are two parallel stacks, as in Module 6. When a dependency is still “path”, the cycle is the part of the path from that package on.

Solution
// Exercise 4: one dependency cycle as a list of names that starts and ends with the same
// package (["api", "auth", "api"]), or null if there is none.
// It must work on a chain of 100,000 packages.
// Depth first with three states and no recursion: `path` is the current path, and next[i] is the
// index of the next dependency to try for path[i] (two parallel stacks).
// O(V + E) time, O(V) memory.
export function findCycle(pkgs: Map<string, string[]>): string[] | null {
  const state = new Map<string, "path" | "done">();
  for (const root of pkgs.keys()) {
    if (state.has(root)) continue;
    const path = [root];
    const next = [0];
    state.set(root, "path");
    while (path.length > 0) {
      const top = path.length - 1;
      const deps = pkgs.get(path[top]) ?? [];
      if (next[top] === deps.length) {
        state.set(path[top], "done"); // every dependency is done
        path.pop();
        next.pop();
        continue;
      }
      const d = deps[next[top]++];
      const s = state.get(d);
      if (s === "path") return [...path.slice(path.indexOf(d)), d]; // the path came back to d
      if (s === undefined) {
        state.set(d, "path");
        path.push(d);
        next.push(0);
      }
    }
  }
  return null;
}

Cost: O(V + E) time, because every package is pushed once and every edge is tried once, plus O(V) for indexOf and slice when a cycle is found. O(V) memory for the states and the two stacks. The recursive answer in slow/ passes the short tests and throws RangeError: Maximum call stack size exceeded on the chain.

Going deeper

You can skip this section. It covers the details the main path left out.

Why Kahn’s algorithm grew faster than O(V + E)

From 100,000 to 400,000 packages, Kahn’s time grew about 2.7 times per doubling, and in four runs it stayed between 2.6 and 2.9. Garbage collection is the engine’s work of freeing memory that nothing uses any more, and it pauses your code while it runs. kahn-growth.ts adds up those pauses inside each timed run: 35.4 ms of 1,126.8 ms at 400,000, so they explain little.

kahn-growth2.ts runs the same algorithm on other inputs. With number keys or with plain arrays, the growth stayed above 2 times. But when each package depended on its three nearest older packages instead of random ones, it took half the time at 400,000 (569.60 against 1,129.15 ms).

So the extra growth comes from neither the Map nor the garbage collector. A CPU cache is a small, fast memory next to the processor that keeps recently read data. The likely cause is that the data outgrows the laptop’s 12 MB cache, and random dependencies make each edge read memory far from the last one. Cache misses were not measured.

Numbers instead of strings for the packages

The packages are keyed by name, so every step of buildOrderKahn looks up a string in a Map. kahn-ids.ts numbers the names once, then keeps the counts in an Int32Array and the lists in an array indexed by number. At 400,000 packages, it took 714.07 ms against 1,147.04 ms. The Big O is the same, O(V + E).

How deep a recursive walk can go

A depth-first walk with recursion has the call stack limit from Module 6, 984 KB by default on x64. There it held between 3,887 and 13,823 frames, depending on the frame size and on whether the function was compiled. On a graph, the depth is the longest path the walk follows, such as a chain of dependencies.

dfs-limit.ts searches for the longest chain buildOrderDfs handles, each try in a fresh process. It found 4,974 packages when the function runs for the first time, and 8,885 after 500 runs on small graphs. Those are close to Module 6’s maxDepth (4,882 and 10,369).

Kahn’s algorithm, allDeps and the breadth-first searches keep their work in an array or a Deque, not on the call stack. So only the memory of the process limits how long a chain they can handle.

Two related problems outside this course

When links arrive one at a time between questions, a structure called union-find answers each “can a reach b” in close to O(1), as Sedgewick and Wayne, section 1.5 explains. When steps can have negative costs, the Bellman-Ford algorithm finds shortest paths in time proportional to E · V, as Sedgewick and Wayne, section 4.4 explains.

Cheat sheet

Figure 10 is the summary of the module: which search fits which sign in a problem.

sign in the problem                          search                    cost
"build after", "depends on", "stages"        Kahn: counts and a queue  O(V + E)
"everything reachable from x"                stack + visited set       O(V + E)
"fewest steps", grid, every step costs 1     BFS + visited set         O(V + E)
"how many groups", "can a reach b"           a walk per unseen node    O(V + E)
"which packages form the cycle"              DFS with three states     O(V + E)
steps with different costs                   Dijkstra (Module 8)       heap

Figure 10: a graph search is O(V + E) as long as a visited set or a count stops it from handling a node twice.

  • Store: adjacency lists, Map<name, name[]> or arrays by number, O(V + E) memory. A matrix only for dense graphs or small V.
  • Walk: a visited set on every graph walk, and a node goes into it when it is pushed. Each node once, each edge once: O(V + E).
  • Fewest steps (every step costs 1): breadth first with a Deque. A grid is a graph, and cell (r, c) is r * cols + c.
  • Order by dependencies: Kahn’s algorithm, counts and a queue. Fewer nodes placed than V means a cycle.
  • Cycle path or post-order: depth first with three states (not seen, path, done), recursive only for short paths.
  • Groups: one walk from every node not yet seen, so one walk per group.
  • Next: Module 8 builds a heap, a structure that always hands back the smallest item, and uses it for shortest paths when steps cost different amounts.

Sources