Courses / DSA Patterns for Working Engineers / Chapter 38
Module 11 · Graph algorithms · Chapter 38 of 39
Advanced Graph Algorithms: Bridges, Strong Components and Euler Paths
Builds on Graphs: Modelling, Breadth-First and Depth-First Search and Topological Sort: Ordering Tasks by Their Dependencies. Next up: Mock Interview: Five Timed Problems With Model Answers.
Part 1 · Introduction to DFS timestamps
Entry times and back edges
A data-centre network, a road map and a package registry all have weak spots: a link or a node whose loss splits the whole into pieces. One depth-first search, with two numbers recorded at each node, finds all of them in time proportional to the size of the graph.
Run a depth-first search on an undirected graph, as in the graphs chapter. Every edge it uses to reach a new node is a tree edge, and together they form the DFS tree of each connected part. In an undirected graph every other edge joins a node to one of its ancestors in that tree. Such an edge is a back edge: the search finds it when it looks at a neighbour that has already been entered.
Number the nodes in the order the search enters them. The entry time tin[v] is that number. The second number, low[v], answers one question: how far back up the tree can the part of the graph hanging below v reach? Formally low[v] is the smallest entry time of any node reachable from v by going down tree edges and then using at most one back edge. The cp-algorithms article on finding bridges defines it the same way: the smallest of tin[v] itself, the entry times of nodes reached from v by a back edge, and the low values of v's children.
A node whose low is smaller than its own tin has a way back up past itself. A node whose low equals its tin is cut off from everything above it except through its parent. The next two lessons turn that into rules for bridges and cut points.
The computation
Updating the numbers needs only the local view of each node, as the search runs. When the search enters v, set both tin[v] and low[v] to the next number from a counter. For every edge at v except the one it came by: if the other end is already entered, that is a back edge, so low[v] becomes the smaller of itself and the other end's tin. If the other end is new, search from it, and when that call returns, low[v] becomes the smaller of itself and the child's low.
Edges are told apart by an id, not by their end nodes. Two edges can join the same pair of nodes, and the search must skip only the one it arrived by, so that the other counts as a back edge. Skipping the parent node would wrongly discard the second edge. The cp-algorithms article reaches the same result with a flag that skips the parent once. A self-loop at v is a neighbour that is already entered, so it is a back edge to v itself and changes nothing.
// An undirected edge [u, v]. Nodes are 0 to n - 1. Repeated edges and // self-loops are allowed. export type Edge = [number, number] // adj[u] lists [neighbour, edge id]. The id tells repeated edges apart. export type Adj = [number, number][][] export function buildAdj(n: number, edges: Edge[]): Adj { const adj: Adj = Array.from({ length: n }, () => []) edges.forEach(([u, v], id) => { if (!Number.isInteger(u) || !Number.isInteger(v)) { throw new RangeError(`edge ${id} is not a pair of whole numbers`) } if (u < 0 || v < 0 || u >= n || v >= n) { throw new RangeError(`edge ${id} is outside 0..${n - 1}`) } adj[u].push([v, id]) adj[v].push([u, id]) // a self-loop is stored twice at u }) return adj }
graph.ts: edges with ids and adjacency lists
import { buildAdj, type Edge } from './graph.ts' // DFS entry times (tin) and low values (low), written with recursion. // low[v] is the smallest entry time reachable from v's subtree using // tree edges downward and at most one back edge. export function timestamps(n: number, edges: Edge[]) { const adj = buildAdj(n, edges) const tin: number[] = new Array(n).fill(-1) const low: number[] = new Array(n).fill(0) let timer = 0 const visit = (v: number, parentEdge: number) => { tin[v] = low[v] = timer++ for (const [to, id] of adj[v]) { if (id === parentEdge) continue // not the edge we came by if (tin[to] !== -1) { low[v] = Math.min(low[v], tin[to]) // a back edge } else { visit(to, id) low[v] = Math.min(low[v], low[to]) } } } for (let s = 0; s < n; s++) if (tin[s] === -1) visit(s, -1) return { tin, low } }
times.ts: entry times and low values, with recursion
Reading the numbers
The demo graph has two triangles joined by one edge, and a node hanging off one triangle. It also runs the awkward inputs: no nodes, one node, a self-loop and a repeated edge.
import { timestamps } from './times.ts' import type { Edge } from './graph.ts' // Two triangles (0-4-6 and 1-2-5) joined by the edge 6-1, with node 3 // hanging off node 2. const edges: Edge[] = [ [0, 4], [4, 6], [6, 0], [6, 1], [1, 2], [2, 5], [5, 1], [2, 3], ] const { tin, low } = timestamps(7, edges) console.log('node ', [0, 1, 2, 3, 4, 5, 6].join(' ')) console.log('tin ', tin.join(' ')) console.log('low ', low.join(' ')) const none = timestamps(0, []) const one = timestamps(1, []) console.log('no nodes:', none.tin.length, ' one node:', one.low) const loop = timestamps(2, [[0, 0], [0, 1], [0, 1]]) const low2 = loop.low.join(' ') console.log('loop, repeat:', loop.tin.join(' '), '/', low2)
times.demo.ts: the numbers on a small network
node 0 1 2 3 4 5 6 tin 0 3 4 6 1 5 2 low 0 3 3 6 0 3 0 no nodes: 0 one node: [ 0 ] loop, repeat: 0 1 / 0 0
Output
The search starts at node 0. Its triangle is 0, 4 and 6, entered at times 0, 1 and 2. Node 6 has a back edge to node 0, so low is 0 for all three nodes, which means each can reach the start of the tree. The edge from 6 to 1 leads to the second triangle, entered at times 3 to 5 for nodes 1, 2 and 5. Node 5 has a back edge to node 1, so nodes 1, 2 and 5 have low 3: they can climb back to node 1 and no higher. Node 3 hangs off node 2 and was entered last, at time 6, and it has no way up, so its low is its own tin, 6.
For the edge cases, an empty graph gives empty arrays, a single node has low 0, and the repeated edge between 0 and 1 gave node 1 a back edge to node 0, so both have low 0.
In the demo, node 2 has tin 4 and low 3. What does that say?
- The part of the tree below node 2 can reach node 1, which was entered at time 3, but nothing earlier.
- The back edge from node 5 to node 1 gives that value.
Why does the search identify the edge it came by with an id and not with the parent node?
Part 2 · Critical links in a data-centre network
The problem
A data-centre network joins servers with links. A link is critical when taking it out leaves some servers unable to reach others that they could reach before. Such a link is called a bridge. Find every critical link, so that you know where to add a second cable.
A first idea is to remove each link in turn and count the connected parts again. That costs a search per link, so time proportional to the links times the size of the graph. The timestamps find all bridges in one search.
Take a tree edge from u down to its child v. If low[v] > tin[u], no edge from the part of the tree below v reaches u or anything entered before u. Every route from that part to the rest of the graph crosses the edge u-v, and it is a bridge. If low[v] <= tin[u], some back edge from below v leads to u or above, which gives a second route around the edge, and it is not a bridge. This is the rule in the cp-algorithms article on bridges. Edges that are not tree edges lie on a cycle with tree edges, so they are never bridges.
Two versions of the search
The recursive search of the last lesson runs out of call stack on a long path. The measurement below builds a path of n servers, which makes the search n levels deep, and finds the largest n that works by doubling and then halving the gap. It ran five times on this machine under Node 24, and a second file runs the version with an explicit stack on 2,00,000 servers.
import type { Edge } from './graph.ts' // A path of n nodes makes the DFS n levels deep. export function path(n: number): Edge[] { const edges: Edge[] = [] for (let i = 0; i + 1 < n; i++) edges.push([i, i + 1]) return edges }
path.ts: a path of n nodes
import { timestamps } from './times.ts' import { path } from './path.ts' const works = (n: number) => { try { timestamps(n, path(n)) return true } catch { return false } } let lo = 1 let hi = 2 while (works(hi)) [lo, hi] = [hi, hi * 2] while (hi - lo > 1) { const mid = (lo + hi) >> 1 if (works(mid)) lo = mid else hi = mid } console.log('recursive version held at', lo, 'nodes in a path')
deep.ts: how deep the recursive search can go
import { lowLinks } from './lowlinks.ts' import { path } from './path.ts' const big = 200_000 const r = lowLinks(big, path(big)) const last = r.low[big - 1] console.log('explicit stack, 200,000 nodes, low of last:', last)
deep.big.ts: the search with an explicit stack
recursive version held at 6239 nodes in a path recursive version held at 6239 nodes in a path recursive version held at 6239 nodes in a path recursive version held at 6271 nodes in a path recursive version held at 6271 nodes in a path explicit stack, 200,000 nodes, low of last: 199999
Output of deep.ts five times, then deep.big.ts
The recursive version held between 6,239 and 6,271 nodes in these runs. That is a limit for this function on this machine, not a general figure: the flood fill of the grid graphs chapter held between 6,143 and 7,199 cells, and other functions hold more or fewer. The version with an explicit stack finishes the path of 2,00,000 nodes. The depth limit depends on the function and the machine, so write the search with an explicit stack when paths can be long.
The explicit-stack version keeps a pointer for each node, next[v], that says which neighbour to try next. A node stays on the stack until all its neighbours are done. When it is finished, its low is passed up to its parent. The result also records the parent of each node, the id of the edge to the parent, and the list of roots, which later lessons need.
Bridges from the numbers
With the numbers in hand, the function is a loop over the tree edges.
import { lowLinks } from './lowlinks.ts' import type { Edge } from './graph.ts' // Ids (positions in `edges`) of the bridges: edges whose removal // leaves some pair of nodes that were connected before disconnected. // A tree edge from u down to v is a bridge when low[v] > tin[u]. export function bridges(n: number, edges: Edge[]): number[] { const { tin, low, parent, parentEdge } = lowLinks(n, edges) const found: number[] = [] for (let v = 0; v < n; v++) { const u = parent[v] if (u !== -1 && low[v] > tin[u]) found.push(parentEdge[v]) } return found.sort((a, b) => a - b) }
bridges.ts: every edge with low[v] > tin[u]
The demo network has a ring of four servers, a tail, and a second ring. It also tries the inputs that matter: a repeated link, a self-loop, no edges, no nodes, a path, a ring and a graph in two separate parts.
import { bridges } from './bridges.ts' import type { Edge } from './graph.ts' // Servers 0 to 7: a ring 0-1-2-3, a tail 3-4-5, a second ring 5-6-7. const links: Edge[] = [ [0, 1], [1, 2], [2, 3], [3, 0], [3, 4], [4, 5], [5, 6], [6, 7], [7, 5], ] const pair = (i: number) => links[i].join('-') const names = (ids: number[]) => ids.map(pair).join(' ') console.log('critical links:', names(bridges(8, links))) const show = (label: string, n: number, e: Edge[]) => console.log(label.padEnd(18), JSON.stringify(bridges(n, e))) show('repeated link 0-1', 3, [[0, 1], [0, 1], [1, 2]]) show('a self-loop', 2, [[0, 0], [0, 1]]) show('no edges', 4, []) show('no nodes', 0, []) show('a path of 4', 4, [[0, 1], [1, 2], [2, 3]]) show('a ring of 4', 4, [[0, 1], [1, 2], [2, 3], [3, 0]]) show('two separate parts', 5, [[0, 1], [2, 3], [3, 4], [4, 2]])
bridges.demo.ts: critical links of a small network
critical links: 3-4 4-5 repeated link 0-1 [2] a self-loop [1] no edges [] no nodes [] a path of 4 [0,1,2] a ring of 4 [] two separate parts [0]
Output
The critical links are 3-4 and 4-5: the tail between the two rings. A repeated link is not critical, because its twin still joins the two servers, while the single link 1-2 next to it is. A self-loop never matters. A graph with no edges has none, every edge of a path is critical, and no edge of a ring is. The last case has two parts: the edge 0-1 is critical and the triangle is not, and the search treats each part separately because the outer loop starts a new search from every node not yet entered.
Checking against removal
The oracle removes each edge and counts connected parts with a union-find structure, the DSU class of the union-find chapter.
import { DSU } from './dsu.ts' import type { Edge } from './graph.ts' // Number of connected components, joining nodes with a DSU. export function components( n: number, edges: Edge[], skip = -1, ): number { const d = new DSU(n) edges.forEach(([u, v], id) => { if (id !== skip) d.union(u, v) }) return d.count }
bridges.oracle.ts: count connected parts
// Oracle: an edge is a bridge when taking it out gives more components. export function bridgesByRemoval(n: number, edges: Edge[]): number[] { const base = components(n, edges) return edges .map((_, id) => id) .filter((id) => components(n, edges, id) > base) }
bridges.oracle.ts: an edge is a bridge if removing it adds a part
import test from 'node:test' import assert from 'node:assert/strict' import { mulberry32 } from './rng.ts' import { bridges } from './bridges.ts' import { bridgesByRemoval } from './bridges.oracle.ts' import { randomEdges } from './rand.ts' test('bridges equal the remove-and-count oracle', () => { const rand = mulberry32(19) for (let i = 0; i < 600; i++) { const n = Math.floor(rand() * 9) const edges = randomEdges(rand, n, Math.floor(rand() * 12)) assert.deepEqual( bridges(n, edges), bridgesByRemoval(n, edges), JSON.stringify([n, edges]), ) } })
bridges.test.ts: bridges against the oracle
✔ bridges equal the remove-and-count oracle (11.1592ms) ℹ tests 1 ℹ suites 0 ℹ pass 1 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 155.7504
Output of node --test
The two methods agree on 600 random graphs of up to 8 nodes, with repeated edges and self-loops allowed. The search takes time proportional to the number of nodes plus edges, once, where the oracle needs a union-find pass per edge.
Related on LeetCode: Critical Connections in a Network. The statements are not reproduced here, and the inputs in this lesson are invented.
A tree edge from u to its child v has low[v] equal to tin[u]. Is it a bridge?
- No. A back edge from below v reaches u itself, so a second route around the edge exists.
Part 3 · Single points of failure
The problem
Now ask about routers, not links. A router is a cut vertex, also called an articulation point, when removing it, together with its links, leaves some of the remaining routers unable to reach each other. These are the single points of failure of a network.
The idea is close to the bridge rule. Take a node u that is not the root of its DFS tree, and one of its children v. If low[v] >= tin[u], nothing below v can climb above u, so every route from that part to the rest of the graph passes through u, and removing u cuts the part off. This is the rule in the cp-algorithms article on cut points. The difference from bridges is the >=: a back edge to u itself does not rescue the part below v when u is removed, since u is gone, while it does rescue the edge u-v when only the edge is removed.
The root needs a separate rule. Every node below the root is in its subtree, so low[v] >= tin[root] is always true and would mark every root. The root is a cut vertex exactly when it has two or more children in the DFS tree, because then those subtrees are joined only through the root. With one child, removing the root leaves the subtree intact.
The function reuses lowLinks, counts the children of each node from the parent array, and applies both rules.
import { lowLinks } from './lowlinks.ts' import type { Edge } from './graph.ts' // Nodes whose removal disconnects some pair of the nodes that remain. // A non-root node u is one when some DFS child v has low[v] >= tin[u]. // A root is one when it has two or more DFS children. export function cutPoints(n: number, edges: Edge[]): number[] { const { tin, low, parent, roots } = lowLinks(n, edges) const cut = new Set<number>() const children: number[] = new Array(n).fill(0) for (let v = 0; v < n; v++) { const u = parent[v] if (u === -1) continue children[u]++ if (parent[u] !== -1 && low[v] >= tin[u]) cut.add(u) } for (const r of roots) if (children[r] >= 2) cut.add(r) return [...cut].sort((a, b) => a - b) }
cutpoints.ts: the two rules for cut vertices
Running it
The demo uses the same network as the bridges lesson. The other runs probe the two rules: the hub of a star, the middle of a path, a ring, a path that does not start at node 0, a single link, repeated links and empty inputs.
import { cutPoints } from './cutpoints.ts' import { bridges } from './bridges.ts' import type { Edge } from './graph.ts' // Routers 0 to 7: a ring 0-1-2-3, a tail 3-4-5, a second ring 5-6-7. const links: Edge[] = [ [0, 1], [1, 2], [2, 3], [3, 0], [3, 4], [4, 5], [5, 6], [6, 7], [7, 5], ] console.log('single points of failure:', cutPoints(8, links)) const show = (label: string, n: number, e: Edge[]) => console.log(label.padEnd(20), JSON.stringify(cutPoints(n, e))) show('a path of 5', 5, [[0, 1], [1, 2], [2, 3], [3, 4]]) show('a star, hub 0', 4, [[0, 1], [0, 2], [0, 3]]) show('a ring of 5', 5, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 0]]) show('path listed from 2', 3, [[2, 1], [1, 0]]) show('a single link', 2, [[0, 1]]) show('repeated links', 3, [[0, 1], [0, 1], [1, 2], [1, 2]]) show('no edges', 3, []) show('no nodes', 0, []) const eight: Edge[] = [[0, 1], [1, 2], [2, 0], [2, 3], [3, 4], [4, 2]] console.log('two rings sharing node 2: cut points', cutPoints(5, eight)) console.log(' bridges', bridges(5, eight))
cutpoints.demo.ts: single points of failure
single points of failure: [ 3, 4, 5 ] a path of 5 [1,2,3] a star, hub 0 [0] a ring of 5 [] path listed from 2 [1] a single link [] repeated links [1] no edges [] no nodes [] two rings sharing node 2: cut points [ 2 ] bridges []
Output
Routers 3, 4 and 5 are the single points of failure: node 3 joins the first ring to the tail, node 4 is the tail's middle, and node 5 joins the tail to the second ring. The middle nodes of a path are cut vertices and its ends are not. The hub of a star is one, and no node of a ring is. In the path whose edges are listed from node 2, the search still starts at node 0, an end of the path. That root has one child and is not a cut vertex, while node 1 is. A single link has no cut vertex, and repeated links change nothing. A graph with no edges or no nodes has none.
The last two lines show that a cut vertex does not need a bridge next to it. Two rings that share node 2 have node 2 as a cut vertex, and no bridge at all, because every edge lies on a ring.
Checking it
The oracle takes each node out in turn, together with its edges, and counts the parts of what remains.
import { components } from './bridges.oracle.ts' import type { Edge } from './graph.ts' // Oracle: delete a node and every edge at it, then count components of // the remaining nodes; more than before means it was a cut point. export function cutPointsByRemoval(n: number, edges: Edge[]): number[] { const before = components(n, edges) const out: number[] = [] for (let x = 0; x < n; x++) { const kept = edges.filter(([u, v]) => u !== x && v !== x) // x stays as a lone node, adding exactly one component if (components(n, kept) - 1 > before) out.push(x) } return out }
cutpoints.oracle.ts: remove a node and count parts
import test from 'node:test' import assert from 'node:assert/strict' import { mulberry32 } from './rng.ts' import { cutPoints } from './cutpoints.ts' import { cutPointsByRemoval } from './cutpoints.oracle.ts' import { randomEdges } from './rand.ts' test('cut points equal the remove-a-node oracle', () => { const rand = mulberry32(23) for (let i = 0; i < 600; i++) { const n = Math.floor(rand() * 9) const edges = randomEdges(rand, n, Math.floor(rand() * 12)) assert.deepEqual( cutPoints(n, edges), cutPointsByRemoval(n, edges), JSON.stringify([n, edges]), ) } })
cutpoints.test.ts: cut vertices against the oracle
✔ cut points equal the remove-a-node oracle (11.0225ms) ℹ tests 1 ℹ suites 0 ℹ pass 1 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 114.5858
Output of node --test
The oracle counts the removed node as one more isolated part, so it subtracts one before comparing. The two agree on 600 random graphs, which include self-loops, repeated edges and isolated nodes. If you write this rule from memory, the likely slip is the root: use children >= 2 for the root and low[v] >= tin[u] for everything else, and test both against an oracle like this one.
Related on LeetCode: Minimum Number of Days to Disconnect Island. The statements are not reproduced here, and the inputs in this lesson are invented.
Why is the test for a cut vertex >= while the test for a bridge is >?
- A bridge removes only the edge, so a back edge to u still rescues the part below; a cut vertex removes u itself, so a back edge to u does not.
Part 4 · Services that reach each other
The problem
A company runs services that call one another. Two services belong together when each can reach the other through calls. A group of services that all reach each other, and cannot be enlarged, is a strongly connected component. Here edges have a direction: a call from A to B is not a call from B to A. The groups matter for deployment, because services in one group can only be started or understood together.
The components partition the nodes. If each component is shrunk to a single node, keeping an edge from component X to component Y when some call goes from a service in X to one in Y, the result is the condensation of the graph. It has no cycles: a cycle between components would merge them into one. So the condensation is a DAG, and the topological sort chapter applies to it.
Kosaraju's algorithm finds the components with two depth-first passes. The first pass searches the graph and records the order in which nodes finish, meaning when their search returns. The second pass builds the reversed graph, with every edge flipped, and searches it starting from nodes in reverse finishing order. Each search tree of the second pass is one component. The cp-algorithms article on strongly connected components describes it this way, with time O(n + m).
The reason it works is in the ordering. The node that finishes last in the first pass lies in a component with no incoming edges from other components. In the reversed graph, that component has no outgoing edges to unvisited ones, so a search from it can only collect its own component. Removing it and repeating gives the components one at a time, source components first.
import type { Edge } from './graph.ts' export type Scc = { comp: number[]; count: number } // Out-neighbours and in-neighbours of a directed graph. function directed(n: number, edges: Edge[]) { const out: number[][] = Array.from({ length: n }, () => []) const into: number[][] = Array.from({ length: n }, () => []) for (const [u, v] of edges) { if (!(u >= 0 && u < n && v >= 0 && v < n)) { throw new RangeError(`edge ${u}->${v} is outside 0..${n - 1}`) } out[u].push(v) into[v].push(u) } return { out, into } }
scc.ts: out-edges and in-edges
// Nodes in the order their DFS call would return, using a stack. function finishOrder(adj: number[][]): number[] { const seen: boolean[] = new Array(adj.length).fill(false) const next: number[] = new Array(adj.length).fill(0) const order: number[] = [] for (let s = 0; s < adj.length; s++) { if (seen[s]) continue seen[s] = true const stack = [s] while (stack.length > 0) { const v = stack[stack.length - 1] if (next[v] < adj[v].length) { const to = adj[v][next[v]++] if (!seen[to]) { seen[to] = true stack.push(to) } } else { order.push(stack.pop()!) // v is finished } } } return order }
scc.ts: the finishing order, with an explicit stack
Running it
The demo has eight services. It prints the component of each, the number of components, and the calls that cross between components, which are the edges of the condensation. It then runs the small cases: no nodes, no edges, one big cycle, and a chain.
import { scc } from './scc.ts' import type { Edge } from './graph.ts' // Services 0 to 7 and the calls between them. const calls: Edge[] = [ [0, 1], [1, 2], [2, 0], [2, 3], [3, 4], [4, 5], [5, 3], [5, 6], [7, 7], ] const { comp, count } = scc(8, calls) console.log('component of each service:', comp.join(' ')) console.log('components:', count) // A call that crosses between two components is an edge of the DAG. const crossing = calls.filter(([u, v]) => comp[u] !== comp[v]) const dag = new Set(crossing.map(([u, v]) => `${comp[u]}->${comp[v]}`)) console.log('calls between components:', [...dag].join(' ')) const comps = (n: number, e: Edge[]) => scc(n, e).comp.join(' ') console.log('no nodes:', scc(0, []).count) console.log('no edges, 3 nodes:', comps(3, [])) const cycle: Edge[] = [[0, 1], [1, 2], [2, 3], [3, 0]] console.log('one cycle of 4:', comps(4, cycle)) console.log('a chain of 4:', comps(4, [[0, 1], [1, 2], [2, 3]]))
scc.demo.ts: components of a call graph
component of each service: 1 1 1 2 2 2 3 0 components: 4 calls between components: 1->2 2->3 no nodes: 0 no edges, 3 nodes: 2 1 0 one cycle of 4: 0 0 0 0 a chain of 4: 0 1 2 3
Output
Services 0, 1 and 2 call each other in a cycle and form component 1, and services 3, 4 and 5 form component 2. Service 6 only receives calls, so it is alone as component 3. Service 7 calls itself and is alone as component 0. Four components, and the calls between them go 1 to 2 and 2 to 3, always from a lower number to a higher one. That is the order the second pass produces, and the test below asserts it for every edge on random graphs. With no edges every node is its own component, one big cycle is one component, and a chain makes one component per node.
Safe services
A service is safe when every chain of calls from it ends at a service that calls nothing, so no chain loops forever. A service is unsafe if it lies on a cycle, or if some chain of calls from it reaches a cycle. The components make this a short computation. A component is unsafe if it holds more than one service, or one service that calls itself, or if some other component it calls is unsafe. Because components come out in topological order, a sweep from the highest number down always sees a component's successors first.
import { scc } from './scc.ts' import type { Edge } from './graph.ts' // A node is safe when every route that starts there ends at a node // with no outgoing edge, so it reaches no cycle. Returns them sorted. // Components come out numbered so that every edge goes from a lower // number to a higher or equal one, so a sweep from the highest number // down sees every successor first. export function safeNodes(n: number, edges: Edge[]): number[] { const { comp, count } = scc(n, edges) const size: number[] = new Array(count).fill(0) for (const c of comp) size[c]++ const bad: boolean[] = size.map((s) => s > 1) // a cycle of 2 or more for (const [u, v] of edges) if (u === v) bad[comp[u]] = true const succ: number[][] = Array.from({ length: count }, () => []) for (const [u, v] of edges) { if (comp[u] !== comp[v]) succ[comp[u]].push(comp[v]) } for (let c = count - 1; c >= 0; c--) { if (succ[c].some((d) => bad[d])) bad[c] = true } const safe: number[] = [] for (let v = 0; v < n; v++) if (!bad[comp[v]]) safe.push(v) return safe }
safe.ts: safe nodes from the components
import { safeNodes } from './safe.ts' import type { Edge } from './graph.ts' // Nodes 0 to 7. 0 -> 1 -> 2 -> 0 is a cycle, 3 leads into it, 4 and 5 // lead only to the sink 6, and 7 loops on itself. const calls: Edge[] = [ [0, 1], [1, 2], [2, 0], [3, 0], [4, 6], [5, 4], [5, 6], [7, 7], ] console.log('safe nodes:', safeNodes(8, calls)) console.log('no nodes:', safeNodes(0, [])) console.log('no edges, 3 nodes:', safeNodes(3, [])) console.log('self-loop only:', safeNodes(1, [[0, 0]])) console.log('a chain of 4:', safeNodes(4, [[0, 1], [1, 2], [2, 3]]))
safe.demo.ts: a call graph with a cycle and a self-loop
safe nodes: [ 4, 5, 6 ] no nodes: [] no edges, 3 nodes: [ 0, 1, 2 ] self-loop only: [] a chain of 4: [ 0, 1, 2, 3 ]
Output
Services 4, 5 and 6 are safe: 4 and 5 lead only to the sink 6. Services 0, 1 and 2 are on a cycle, 3 calls into it, and 7 calls itself, so none of those is safe. With no edges every node is safe, a lone self-loop is not, and in a chain every node is.
Checking both
The first oracle computes which services can reach which, by allowing one more intermediate service at a time, and says two services are in one component when each reaches the other. The second repeatedly removes services that have no call to a service still present; the services removed are the safe ones.
import type { Edge } from './graph.ts' // Oracle: reach[u][v] is true when a route leads from u to v. It // comes from repeatedly allowing one more intermediate node. export function reachability(n: number, edges: Edge[]): boolean[][] { const r = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => i === j), ) for (const [u, v] of edges) r[u][v] = true for (let k = 0; k < n; k++) { for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) r[i][j] ||= r[i][k] && r[k][j] } } return r }
scc.oracle.ts: who can reach whom
// Oracle for safe nodes: keep removing nodes that have no outgoing // edge to a node that is still there. export function safeByPeeling(n: number, edges: Edge[]): number[] { const alive = new Array<boolean>(n).fill(true) for (let changed = true; changed;) { changed = false for (let v = 0; v < n; v++) { if (alive[v] && !edges.some(([a, b]) => a === v && alive[b])) { alive[v] = false changed = true } } } return [...alive.keys()].filter((v) => !alive[v]) }
scc.oracle.ts: remove services that call nothing
import test from 'node:test' import assert from 'node:assert/strict' import { mulberry32 } from './rng.ts' import { scc } from './scc.ts' import { reachability } from './scc.oracle.ts' import { randomEdges } from './rand.ts' test('components match mutual reachability and come in order', () => { const rand = mulberry32(29) for (let i = 0; i < 500; i++) { const n = Math.floor(rand() * 9) const edges = randomEdges(rand, n, Math.floor(rand() * 16)) const { comp } = scc(n, edges) const r = reachability(n, edges) for (let u = 0; u < n; u++) { for (let v = 0; v < n; v++) { assert.equal(comp[u] === comp[v], r[u][v] && r[v][u]) } } for (const [u, v] of edges) assert.ok(comp[u] <= comp[v]) } })
scc.test.ts: components against mutual reachability
import test from 'node:test' import assert from 'node:assert/strict' import { mulberry32 } from './rng.ts' import { safeNodes } from './safe.ts' import { safeByPeeling } from './scc.oracle.ts' import { randomEdges } from './rand.ts' test('safe nodes equal the peeling oracle', () => { const rand = mulberry32(30) for (let i = 0; i < 500; i++) { const n = Math.floor(rand() * 9) const edges = randomEdges(rand, n, Math.floor(rand() * 14)) assert.deepEqual(safeNodes(n, edges), safeByPeeling(n, edges)) } })
safe.test.ts: safe nodes against the peeling oracle
Part 5 · A trip that uses every ticket once
The problem
A traveller holds one-way tickets between towns. Is there a trip that uses every ticket exactly once, and if so, which one comes first in alphabetical order? A walk that uses every edge of a graph exactly once is an Euler path. An Euler circuit is one that ends where it started.
When can it exist? For an undirected graph, the cp-algorithms article on Euler paths says a circuit exists exactly when every node has even degree, and a path when exactly two nodes have odd degree, ignoring nodes with no edges and provided the edges form one connected piece. For tickets, which are directed, the same idea applies to out-degree and in-degree. Count, for each town, tickets leaving minus tickets arriving. A path needs every difference to be 0, except for at most one town with +1, where the trip starts, and one with -1, where it ends. If all differences are 0, the trip is a circuit and can start at any town with a ticket. The directed rule is checked against a brute-force enumeration below, since the cp-algorithms article covers only the undirected case.
The degrees are necessary but not sufficient. Two separate loops of tickets satisfy every degree condition, yet no trip uses all of them, because the loops are not connected. Hierholzer's algorithm finds a trip and also detects this case.
Hierholzer's algorithm
Hierholzer's algorithm keeps a stack that holds the walk so far. At the top town it takes an unused ticket, if one remains, and pushes the town it leads to. If the top town has no unused ticket, the walk is stuck there, so that town is final in the trip: it is popped and appended to the result. Popping continues until a town with unused tickets is found, where the algorithm starts a new loop that will be spliced in. At the end the result holds the trip in reverse. If it has one more town than there are tickets, every ticket was used. If not, some tickets were unreachable and no trip exists. The cp-algorithms article describes the same stack method and gives its time as linear in the number of edges, O(M).
To get the alphabetical order, sort each town's tickets so that the smallest destination is taken first. Taking the smallest first gives the smallest trip, and the brute-force check below confirms it on random graphs.
export type Arc = [number, number] // one-way: from, to // Can the degrees allow a path? Every node needs out = in, except at // most one start with out = in + 1 and one end with in = out + 1. function degreesAllow( n: number, arcs: Arc[], ): { start: number } | null { const diff: number[] = new Array(n).fill(0) // out minus in for (const [u, v] of arcs) { diff[u]++ diff[v]-- } const starts = [...diff.keys()].filter((v) => diff[v] === 1) const ends = [...diff.keys()].filter((v) => diff[v] === -1) const flat = diff.every((d) => d >= -1 && d <= 1) if (!flat || starts.length > 1 || starts.length !== ends.length) return null if (starts.length === 1) return { start: starts[0] } const first = arcs.map(([u]) => u).reduce((a, b) => Math.min(a, b)) return { start: first } // every node balanced: a circuit, any start }
euler.ts: can the degrees allow a path
// Hierholzer's algorithm. Returns the nodes of a path that uses every // arc once, taking the smallest next node at every choice, or null if // no such path exists. No arcs gives an empty path. export function eulerPath(n: number, arcs: Arc[]): number[] | null { if (arcs.length === 0) return [] const out: number[][] = Array.from({ length: n }, () => []) for (const [u, v] of arcs) out[u].push(v) const plan = degreesAllow(n, arcs) if (!plan) return null for (const list of out) list.sort((a, b) => b - a) // smallest on top const stack = [plan.start] const path: number[] = [] while (stack.length > 0) { const v = stack[stack.length - 1] if (out[v].length > 0) stack.push(out[v].pop()!) // walk on else path.push(stack.pop()!) // stuck: v is final in the path } path.reverse() return path.length === arcs.length + 1 ? path : null }
euler.ts: Hierholzer with the smallest town first
Running it
The demo has five towns with invented names, numbered in alphabetical order so that smaller number means earlier in the alphabet.
import { eulerPath, type Arc } from './euler.ts' // Tickets between five invented towns, numbered in alphabetical order. const towns = ['Alp', 'Brav', 'Clam', 'Dorn', 'Elm'] const id = (t: string) => towns.indexOf(t) const tickets: [string, string][] = [ ['Alp', 'Brav'], ['Brav', 'Clam'], ['Clam', 'Alp'], ['Alp', 'Dorn'], ['Dorn', 'Elm'], ['Elm', 'Alp'], ['Clam', 'Brav'], ] const arcs: Arc[] = tickets.map(([a, b]) => [id(a), id(b)]) const route = eulerPath(5, arcs) console.log('route:', route?.map((v) => towns[v]).join(' > ')) const rows = (a: Arc[]) => JSON.stringify(eulerPath(5, a)) console.log('no tickets :', rows([])) console.log('one ticket :', rows([[3, 1]])) console.log('a self-loop :', rows([[2, 2]])) console.log('two cycles apart:', rows([[0, 1], [1, 0], [2, 3], [3, 2]])) console.log('degrees wrong :', rows([[0, 1], [0, 2]])) console.log('tickets twice :', rows([[0, 1], [1, 0], [0, 1], [1, 0]]))
euler.demo.ts: a trip over seven tickets, then edge cases
route: Clam > Alp > Dorn > Elm > Alp > Brav > Clam > Brav no tickets : [] one ticket : [3,1] a self-loop : [2,2] two cycles apart: null degrees wrong : null tickets twice : [0,1,0,1,0]
Output
The trip starts at Clam, the only town with one more ticket out than in, and ends at Brav: Clam, Alp, Dorn, Elm, Alp, Brav, Clam, Brav. It is not the greedy walk. Taking the smallest ticket at every step from Alp leads to Brav, Clam, Brav and a dead end with the Dorn tickets unused. Hierholzer backs up and splices the loop Alp, Dorn, Elm, Alp in. The scene replays this run from a copy of the loop that logs each step, with a ring on the town where the walk currently stands and the finished towns along the bottom.
start at Clam walk Clam > Alp walk Alp > Brav walk Brav > Clam walk Clam > Brav stuck at Brav: finished stuck at Clam: finished stuck at Brav: finished walk Alp > Dorn walk Dorn > Elm walk Elm > Alp stuck at Alp: finished stuck at Elm: finished stuck at Dorn: finished stuck at Alp: finished stuck at Clam: finished route: Clam > Alp > Dorn > Elm > Alp > Brav > Clam > Brav
The logged walk
Checking it
The oracle tries every order of using the tickets, from every start, keeps those that use them all and returns the smallest by comparing the town sequences. It runs only on small graphs.
import type { Arc } from './euler.ts' // Oracle: try every order of using the arcs, from every start node, // and keep the smallest node sequence of all the orders that work. export function smallestByEnumeration(n: number, arcs: Arc[]) { if (arcs.length === 0) return [] const used = new Array<boolean>(arcs.length).fill(false) let best: number[] | null = null const smaller = (a: number[], b: number[]) => { for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] < b[i] return false } const go = (path: number[]) => { if (path.length === arcs.length + 1) { if (best === null || smaller(path, best)) best = [...path] return } const here = path[path.length - 1] arcs.forEach(([u, v], i) => { if (used[i] || u !== here) return used[i] = true go([...path, v]) used[i] = false }) } for (let s = 0; s < n; s++) go([s]) return best }
euler.oracle.ts: try every order of the tickets
import test from 'node:test' import assert from 'node:assert/strict' import { mulberry32 } from './rng.ts' import { eulerPath, type Arc } from './euler.ts' import { smallestByEnumeration } from './euler.oracle.ts' test('Hierholzer equals the smallest path by enumeration', () => { const rand = mulberry32(37) let found = 0 for (let i = 0; i < 1500; i++) { const n = 1 + Math.floor(rand() * 5) const arcs: Arc[] = [] for (let k = Math.floor(rand() * 8); k > 0; k--) { arcs.push([Math.floor(rand() * n), Math.floor(rand() * n)]) } const want = smallestByEnumeration(n, arcs) assert.deepEqual( eulerPath(n, arcs), want, JSON.stringify([n, arcs]), ) if (want !== null) found++ } assert.ok(found > 100) // many of the random graphs do have a path console.log('graphs that had a path:', found, 'of 1500') })
euler.test.ts: Hierholzer against enumeration
graphs that had a path: 937 of 1500 ✔ Hierholzer equals the smallest path by enumeration (60.0835ms) ℹ tests 1 ℹ suites 0 ℹ pass 1 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 158.197
Output of node --test
On 1,500 random ticket sets of up to 7 tickets on up to 5 towns, the answers agree, including the null answers, and 937 of the sets had a trip, so the check is not only on empty cases.
Related on LeetCode: Reconstruct Itinerary, Valid Arrangement of Pairs. The statements are not reproduced here, and the inputs in this lesson are invented.
Part 6 · A code that covers every combination
The problem
A digital safe has a keypad that accepts every typed digit one after another and opens as soon as the last n digits typed equal the code. With k different digits there are k^n codes. What is the shortest string of digits that, typed once, contains every n-digit code?
A string of length L has L - n + 1 windows of n digits, and each of the k^n codes needs a window of its own, so L is at least k^n + n - 1. The question is whether that length can be reached. A de Bruijn sequence shows that it can. The Wikipedia article on de Bruijn sequences defines B(k, n) as a cyclic sequence over k symbols in which every string of n symbols appears exactly once, which has length k^n. Unrolled into a line, by repeating its first n - 1 symbols at the end, it contains every code and has the length k^n + n - 1 that the bound requires.
Building it with an Euler circuit
The sequence is an Euler circuit in a graph. Make one node for each string of n - 1 digits, so k^(n-1) nodes. For each code of n digits, add an edge from the node for its first n - 1 digits to the node for its last n - 1 digits, labelled with its last digit. There are k^n edges, k out of every node and k into every node, so every degree condition holds. The graph is also connected: from any node you can reach any other by appending the digits of the target one at a time, which takes n - 1 steps. So an Euler circuit exists. Following the circuit, each edge adds one digit, and consecutive edges overlap in n - 1 digits, so every code is spelled exactly once. The Wikipedia article states the same link between Euler circuits and de Bruijn sequences.
Number the nodes as the whole numbers 0 to k^(n-1) - 1, reading the digits as a base-k number. An edge with digit d leaves node x for node (x * k + d) % k^(n-1): drop the first digit, append d. Hierholzer's algorithm then runs on an implicit graph. At each node the unused edges are the digits not yet tried, so a counter per node is enough.
export function deBruijn(k: number, n: number): string { if (!Number.isInteger(k) || k < 1 || k > 10) { throw new RangeError('k must be a whole number from 1 to 10') } if (!Number.isInteger(n) || n < 1) throw new RangeError('n must be 1 or more') if (k ** n > 10_000_000) throw new RangeError( 'k^n is over ten million: the string would be too long', ) const nodes = k ** (n - 1) const nextDigit: number[] = new Array(nodes).fill(0) // next to try // Each entry is [node, digit of the edge that led here]. const stack: [number, number][] = [[0, -1]] const digits: number[] = [] while (stack.length > 0) { const [x] = stack[stack.length - 1] if (nextDigit[x] < k) { const d = nextDigit[x]++ stack.push([(x * k + d) % nodes, d]) } else { const [, d] = stack.pop()! if (d >= 0) digits.push(d) // a finished edge, in reverse order } } digits.reverse() // k^n digits: the circuit as a cyclic sequence const text = digits.join('') // Unroll the circle: repeat its start to add n - 1 digits. return text + text.repeat(n).slice(0, n - 1) }
debruijn.ts: a de Bruijn string with Hierholzer
Running it
The demo prints the string for several (k, n) pairs and checks that it contains every code, by collecting all windows of n digits into a set.
import { deBruijn } from './debruijn.ts' const covers = (s: string, k: number, n: number) => { const seen = new Set<string>() for (let i = 0; i + n <= s.length; i++) seen.add(s.slice(i, i + n)) return seen.size === k ** n } const show = (k: number, n: number) => { const s = deBruijn(k, n) const text = s.length <= 24 ? s : s.slice(0, 24) + '...' const ok = covers(s, k, n) console.log(`k=${k} n=${n}:`, text, 'length', s.length, 'covers', ok) } show(3, 2) show(2, 3) show(2, 4) show(10, 2) show(10, 3) show(1, 3) show(4, 1) for (const [k, n] of [[0, 2], [11, 2], [2, 0], [10, 8]]) { try { deBruijn(k, n) } catch (e) { console.log(`k=${k} n=${n}:`, (e as Error).message) } }
debruijn.demo.ts: strings for several k and n
k=3 n=2: 0102112200 length 10 covers true k=2 n=3: 0101110001 length 10 covers true k=2 n=4: 0100110101111000010 length 19 covers true k=10 n=2: 010203040506070809112131... length 101 covers true k=10 n=3: 010020030040050060070080... length 1002 covers true k=1 n=3: 000 length 3 covers true k=4 n=1: 0123 length 4 covers true k=0 n=2: k must be a whole number from 1 to 10 k=11 n=2: k must be a whole number from 1 to 10 k=2 n=0: n must be 1 or more k=10 n=8: k^n is over ten million: the string would be too long
Output
For three digits and codes of two digits the string has 10 digits, 0102112200, and holds all nine codes. For two digits and three-digit codes it is 0101110001, length 10. The two-digit codes over ten digits take 101 digits and the three-digit codes take 1,002, and each contains every code, which is 10^n + n - 1 in both cases. A single code symbol (k = 1) gives 000, and codes of one digit give the digits in order. Invalid sizes throw, and so does a size whose k^n is over 1 crore, since the string would be longer than that.
The case k = 1 is the one that breaks a shorter way of unrolling the circle. Writing text + text.slice(0, n - 1) takes the first n - 1 digits of the circle, but when the circle is shorter than n - 1 there are not enough of them. For k = 1 and n = 3 the circle is the single digit 0. The code repeats the circle before taking the slice.
// Unrolling for k = 1, n = 3: the circle is the single digit 0. const circle = '0' const n = 3 const short = circle + circle.slice(0, n - 1) const fixed = circle + circle.repeat(n).slice(0, n - 1) console.log('slice only :', short, 'length', short.length) console.log('repeat first:', fixed, 'length', fixed.length)
debruijn.slip.ts: the two ways of unrolling, for k = 1 and n = 3
Checking it
The first test runs every pair with k up to 6 and n up to 4 whose code count is at most 5,000 and asserts the length k^n + n - 1 and that every code is present. The second test confirms that the length cannot be improved: for four small pairs it tries every string of one digit fewer and checks that none contains every code, which also agrees with the counting argument above.
import test from 'node:test' import assert from 'node:assert/strict' import { deBruijn } from './debruijn.ts' const codes = (s: string, n: number) => { const seen = new Set<string>() for (let i = 0; i + n <= s.length; i++) seen.add(s.slice(i, i + n)) return seen } test('every code appears and the length is k^n + n - 1', () => { for (let k = 1; k <= 6; k++) { for (let n = 1; n <= 4; n++) { if (k ** n > 5000) continue const s = deBruijn(k, n) assert.equal(s.length, k ** n + n - 1) assert.equal(codes(s, n).size, k ** n) } } })
debruijn.test.ts: coverage and length
import test from 'node:test' import assert from 'node:assert/strict' // Distinct windows of n digits in s. const codes = (s: string, n: number) => { const seen = new Set<string>() for (let i = 0; i + n <= s.length; i++) seen.add(s.slice(i, i + n)) return seen } test('no string one digit shorter holds every code', () => { for (const [k, n] of [ [2, 2], [2, 3], [3, 2], [2, 4], ]) { const length = k ** n + n - 2 for (let x = 0; x < k ** length; x++) { const s = x.toString(k).padStart(length, '0') assert.ok(codes(s, n).size < k ** n) } } })
debruijn.short.test.ts: nothing shorter works
✔ every code appears and the length is k^n + n - 1 (3.0885ms) ℹ tests 1 ℹ suites 0 ℹ pass 1 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 114.8953
Output of the coverage test
✔ no string one digit shorter holds every code (281.6166ms) ℹ tests 1 ℹ suites 0 ℹ pass 1 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 386.6355
Output of the minimality test
The time is proportional to the number of edges, k^n, which is also the length of the output, so the method suits moderate sizes. Four-digit codes over ten digits need a string of 10,003 digits, and six-digit codes need more than 10 lakh.
Related on LeetCode: Cracking the Safe. The statements are not reproduced here, and the inputs in this lesson are invented.
All chapters · Previous: Minimum Spanning Trees: Kruskal and Prim