Part 1 · Introduction to graphs and breadth-first search
Things and links
A metro map, a company's reporting lines and a set of project dependencies are all graphs: things joined by links. Searching them well starts with choosing a search order, nearest first or deepest first.
A graph is a set of nodes (also called vertices) and a set of edges, each joining two nodes. In an undirected graph an edge works both ways, like a metro track. In a directed graph each edge has a direction, like a one-way road or a reporting line. A path is a chain of edges, a graph is connected when a path joins every pair of nodes, and the degree of a node is the number of edges at it. In a directed graph the in-degree, already used in the topological sort chapter, counts edges arriving and the out-degree counts edges leaving.
Every graph in this chapter has nodes numbered 0 to n - 1, because array indexes are the cheapest names. Edges arrive as a list of [u, v] pairs, so the first job is to turn that list into an adjacency list: for each node, the array of its neighbours. Reading all neighbours of one node then costs the node's degree, and the whole structure takes space proportional to the nodes plus the edges.
Code blocks follow the convention set out in the first chapter.
ts
exporttype Edge = [number, number]
// Adjacency lists for nodes 0..n-1 from an edge list.exportfunction buildAdj(n: number, edges: Edge[], directed = false) {
const adj: number[][] = Array.from({ length: n }, () => [])
const ok = (x: number) => Number.isInteger(x) && x >= 0 && x < n
for (const [u, v] of edges) {
if (!(ok(u) && ok(v))) {
thrownew RangeError(`edge ${u},${v} is outside 0..${n - 1}`)
}
adj[u].push(v)
if (!directed) adj[v].push(u)
}
return adj
}
lib.ts: the edge type and the adjacency list builder
An undirected edge is stored twice, once at each end. A self-loop [u, u] is therefore stored twice at u, and a repeated edge is stored twice at both ends. The builder keeps such input as given and rejects anything that is not a whole node number in the range, which would otherwise crash later with a less helpful message.
Breadth-first search
Breadth-first search (BFS) visits the start node, then everything one edge away, then everything two edges away, and so on. It uses a queue, first in first out, so nodes leave in the order they entered. The queue here is an array with a head index that moves forward, never shift().
The result is the number of hops from the start to every node, which is the length of a shortest path when every edge counts as one. The array of distances also records which nodes have been seen: -1 means not yet.
ts
// Hops from start to every node; -1 where a node cannot be reached.exportfunction bfs(adj: number[][], start: number): number[] {
const dist: number[] = new Array(adj.length).fill(-1)
const queue: number[] = [start]
dist[start] = 0for (let head = 0; head < queue.length; head++) {
const u = queue[head]
for (const v of adj[u]) {
if (dist[v] === -1) {
dist[v] = dist[u] + 1
queue.push(v)
}
}
}
return dist
}
lib.ts: BFS returning hop counts
Why are the counts shortest? The queue always holds nodes of distance d followed by nodes of distance d + 1, never anything else. A node at distance d + 1 can only be queued by a node at distance d, and every node at distance d is processed before any at d + 1. So the first time a node is reached is by a shortest route.
Here are eight made-up metro stations and nine tracks between them, searched from Ash.
Ash hops 0
Bay hops 1
Cove hops 1
Dune hops 2
Elm hops 2
Fort hops 3
Glen hops 3
Hill hops 4
Output of one run
Animated sceneBFS over eight stations0:26
Watch for each station getting its hop count when it joins the queue
Read it as steps
hop counts grow as stations join the queue
Notice that Hill gets 4 even though it touches both Fort and Glen: it is marked the first time a neighbour reaches it, and the later edge finds it already marked. Each station is marked once, and that is what keeps the search linear.
Reachability comes for free. To ask whether any path joins two nodes, search from one and see whether the other was reached: bfs(adj, a)[b] !== -1. Related on LeetCode: Find if Path Exists in Graph.
Mark on enqueue, and why the head index
The line dist[v] = dist[u] + 1 runs at the moment a node is queued. Marking at that moment means a node can never be queued twice. If you instead mark a node when it leaves the queue, a node reachable by several edges is queued once per edge before its first turn comes.
ts
// Pushes when a node is marked on enqueue, and when marked on dequeue.function pushCounts(adj: number[][], start: number) {
const seen: boolean[] = new Array(adj.length).fill(false)
seen[start] = trueconst q1 = [start]
for (let h = 0; h < q1.length; h++)
for (const v of adj[q1[h]]) {
if (!seen[v]) {
seen[v] = true
q1.push(v)
}
}
const done: boolean[] = new Array(adj.length).fill(false)
const q2 = [start]
for (let h = 0; h < q2.length; h++) {
const u = q2[h]
if (done[u]) continue
done[u] = truefor (const v of adj[u]) if (!done[v]) q2.push(v)
}
return { onEnqueue: q1.length, onDequeue: q2.length }
}
Two versions that count pushes: mark on enqueue, then on dequeue
ts
function randomEdges(n: number, m: number, seed: number): Edge[] {
const rand = mulberry32(seed)
const out: Edge[] = []
while (out.length < m) {
const a = Math.floor(rand() * n)
const b = Math.floor(rand() * n)
if (a !== b) out.push([a, b])
}
return out
}
const complete: Edge[] = []
for (let a = 0; a < 100; a++) {
for (let b = a + 1; b < 100; b++) complete.push([a, b])
}
const dense = buildAdj(100, complete)
console.log('complete 100 nodes', pushCounts(dense, 0))
const sparse = buildAdj(1000, randomEdges(1000, 5000, 4))
console.log('1000 nodes, 5000 edges', pushCounts(sparse, 0))
A 100-node complete graph and a 1,000-node graph with 5,000 random edges
Marking on enqueue pushes each node once. Marking on dequeue pushed about once per edge here: 4,951 pushes for the complete graph, which has 4,950 edges, and 5,001 for the random one, which has 5,000. In general each edge pushes at most once, plus one push for the start. The search still finishes, but the queue grows to the number of edges instead of the number of nodes.
The same function behaves sensibly on awkward input. One node alone gives [0], a second component stays at -1, a self-loop and a repeated edge change nothing, and a bad node number, a fraction included, is rejected. The searches do not check start: a start that is not a node of the graph, as in bfs(buildAdj(3, []), 5), throws a TypeError from inside the loop, so pass a node that exists.
Last, the queue. Array.prototype.shift() removes the first element, and the language does not say how fast it must do so. On this machine, draining a queue with shift() slowed down much faster than the queue grew, while the head index stayed flat. The times vary between runs.
ts
function drainShift(n: number): number {
const q = Array.from({ length: n }, (_, i) => i)
const t = performance.now()
let sum = 0while (q.length > 0) sum += q.shift()!
return performance.now() - t
}
function drainHead(n: number): number {
const q = Array.from({ length: n }, (_, i) => i)
const t = performance.now()
let sum = 0for (let head = 0; head < q.length; head++) sum += q[head]
return performance.now() - t
}
for (const n of [10_000, 50_000, 100_000, 200_000]) {
const a = drainShift(n).toFixed(1)
const b = drainHead(n).toFixed(1)
console.log(`n=${n}: shift ${a} ms, head index ${b} ms`)
}
Draining an array queue two ways
text
n=10000: shift 1.9 ms, head index 0.3 ms
n=50000: shift 106.2 ms, head index 0.1 ms
n=100000: shift 430.4 ms, head index 0.5 ms
n=200000: shift 2368.8 ms, head index 1.1 ms
Output of one run; times vary
A graph has 1,000 nodes and 5,000 edges and is connected. Marking nodes when they leave the queue pushed 5,001 entries. How many pushes does marking on enqueue make, and why?
Exactly 1,000: each node is marked as it is queued, so no edge can queue it again.
What does bfs return for a node in another component?
-1. The distance array starts at -1 for every node and only reached nodes are changed.
Why does the first time BFS reaches a node give a shortest route?
Nodes leave the queue in order of distance, and a node can only be queued by a node one hop closer, so no shorter route was left unexplored.
Part 2 · Depth-first search with an explicit stack, and cycles
Going as deep as possible
Depth-first search (DFS) follows one edge after another until it reaches a node with nothing new to visit, then backs up to the nearest node that still has an unvisited neighbour. Where BFS spreads in rings, DFS dives. It is the search behind cycle detection, and the topological sort chapter uses it for ordering.
The shortest way to write it is recursion. The call stack remembers where each node was left, and returning from a call is the backing up.
ts
exportfunction dfsRec(adj: number[][], start: number): number[] {
const seen: boolean[] = new Array(adj.length).fill(false)
const order: number[] = []
const visit = (u: number): void => {
seen[u] = true
order.push(u)
for (const v of adj[u]) if (!seen[v]) visit(v)
}
visit(start)
return order
}
dfs.ts: recursive DFS returning the visiting order
The order in which nodes are visited depends on the order of each adjacency list. A different edge order gives a different, equally valid DFS, so compare orders only for the same adjacency lists.
The same search with your own stack
Recursion has a limit. Each call takes stack space, and a long chain of nodes can use all of it. Here is a path graph of 1,00,000 nodes, searched both ways.
ts
const n = 100_000
const chain = Array.from({ length: n }, (_, i) =>
i + 1 < n ? [i + 1] : [],
)
try {
console.log('recursive reached', dfsRec(chain, 0).length)
} catch (e) {
const err = e as Error
console.log('recursive:', err.name + ':', err.message)
}
console.log('iterative reached', dfs(chain, 0).length)
A chain of 1,00,000 nodes
text
recursive: RangeError: Maximum call stack size exceeded
iterative reached 100000
Output of one run
The recursive version fails with a RangeError. How deep it gets depends on the function and the machine. In ten runs of the file below on this machine, on Windows and in WSL, this function failed somewhere between about 5,500 and 8,000 nested calls, and the same file gave different figures on different runs, so never rely on more than a few thousand. The tree DFS chapter measures a lighter function that survives about 12,000 calls, and the topological sort chapter one that stops near 9,600. These figures do not contradict each other: the limit depends on the function, because each call takes its own amount of stack, and on the machine.
ts
// Deepest chain the recursive version survives, found by doubling.function survives(n: number): boolean {
const chain = Array.from({ length: n }, (_, i) =>
i + 1 < n ? [i + 1] : [],
)
try {
return dfsRec(chain, 0).length === n
} catch {
returnfalse
}
}
let lo = 1000while (survives(lo * 2)) lo *= 2let hi = lo * 2while (hi - lo > 100) {
const mid = (lo + hi) >> 1if (survives(mid)) lo = mid
else hi = mid
}
console.log(`recursion held at ${lo} nodes and failed at ${hi}`)
Finding the last chain that survives (this block uses dfsRec)
text
recursion held at 7937 nodes and failed at 8000
Output of one run; the figure varies between runs
The fix is to keep the pending calls in an array you own, whose size is limited by memory and not by the call stack. Each entry is a frame: the node and the index of the next neighbour to try. The loop looks at the top frame, tries its next neighbour, and pops the frame when the neighbours run out. Popping is the return.
ts
// Same order as dfsRec, but the pending calls live in an array.// Each frame is [node, index of the next neighbour to try].exportfunction dfs(adj: number[][], start: number): number[] {
const seen: boolean[] = new Array(adj.length).fill(false)
const order: number[] = [start]
seen[start] = trueconst stack: [number, number][] = [[start, 0]]
while (stack.length > 0) {
const frame = stack[stack.length - 1]
const [u, i] = frame
if (i === adj[u].length) {
stack.pop() // every neighbour tried: the call returnscontinue
}
frame[1]++
const v = adj[u][i]
if (!seen[v]) {
seen[v] = true
order.push(v)
stack.push([v, 0])
}
}
return order
}
dfs.ts: iterative DFS with frames
This visits nodes in exactly the order the recursive version does, because the frame remembers the same place the call would have. That matters whenever you need the moment a node finishes, as the colouring below does. The simpler trick of pushing every neighbour at once and marking nodes when they are popped is a valid search, but it need not give the same order and it has no finishing moment.
Colours and cycles
To find a cycle in a directed graph, give each node one of three colours: 0 not yet seen, 1 open (on the stack, its neighbours still being explored) and 2 done. An edge that reaches an open node closes a loop, because the open nodes form a chain of edges that leads from that open node down to the node you are leaving, so the new edge completes a loop.
Marking nodes only as seen is not enough. In a diamond, where node 0 points to 1 and 2 and both point to 3, node 3 is reached twice, and that is not a cycle. The colour tells the two cases apart: when the second edge reaches node 3 it is already done, not open.
ts
// True when a directed graph has a cycle.// Colours: 0 new, 1 on the stack, 2 done.exportfunction hasCycle(adj: number[][]): boolean {
const colour: number[] = new Array(adj.length).fill(0)
for (let s = 0; s < adj.length; s++) {
if (colour[s] !== 0) continue
colour[s] = 1const stack: [number, number][] = [[s, 0]]
while (stack.length > 0) {
const frame = stack[stack.length - 1]
const [u, i] = frame
if (i === adj[u].length) {
colour[u] = 2
stack.pop()
continue
}
frame[1]++
const v = adj[u][i]
if (colour[v] === 1) returntrue// edge back to the open pathif (colour[v] === 0) {
colour[v] = 1
stack.push([v, 0])
}
}
}
returnfalse
}
dfs.ts: cycle test for a directed graph
Animated sceneAn edge back to an open node0:18
Watch for the edge that returns to a node still on the stack
Read it as steps
the edge from D back to B closes a loop
In the scene, A, B, C and D are all open when the edge from D reaches B. B is still on the stack, so the edge closes the loop B, C, D. Node E is never visited because the search stops at the first cycle it finds.
recursive: 0134256
iterative: 0134256
ring true diamond false
self-loop true
empty false one node false
Output of one run
In an undirected graph the rule changes, because every edge shows up twice and going back along the edge you arrived by is not a cycle. The test skips only that one edge, identified by its position in the edge list, and treats any other edge to a seen node as a cycle. Two parallel edges and a self-loop then count as cycles, which is the usual meaning.
ts
type Edge = [number, number]
// Cycle test for an undirected graph. Frames also remember the edge// used to arrive, so only that edge, not every edge back to the parent,// is skipped. Parallel edges and self-loops therefore count as cycles.exportfunction hasCycleUndirected(n: number, edges: Edge[]): boolean {
const adj: [number, number][][] = Array.from({ length: n }, () => [])
edges.forEach(([a, b], id) => {
adj[a].push([b, id])
adj[b].push([a, id])
})
const seen: boolean[] = new Array(n).fill(false)
dfs.ts: cycle test for an undirected graph, part 1
ts
for (let s = 0; s < n; s++) {
if (seen[s]) continue
seen[s] = trueconst stack: [number, number, number][] = [[s, 0, -1]]
while (stack.length > 0) {
const frame = stack[stack.length - 1]
const [u, i, via] = frame
if (i === adj[u].length) {
stack.pop()
continue
}
frame[1]++
const [v, id] = adj[u][i]
if (id === via) continueif (seen[v]) returntrue
seen[v] = true
stack.push([v, 0, id])
}
}
returnfalse
}
dfs.ts, part 2: the search with the arriving edge in each frame
path false
triangle true
same edge twice true
self-loop true
two parts false
Output of one run
Checking against brute force
Both tests are checked against methods that share no code with them: a directed graph has a cycle exactly when some node can reach itself, and an undirected graph with c components is a forest exactly when it has n - c edges.
function randomEdges(rand: () => number, n: number, m: number): Edge[] {
const out: Edge[] = []
for (let i = 0; i < m; i++) {
out.push([Math.floor(rand() * n), Math.floor(rand() * n)])
}
return out
}
A random edge list, and a reachability check
ts
// A directed graph has a cycle exactly when some node reaches itself.function bruteCycle(n: number, edges: Edge[]): boolean {
const reach = Array.from({ length: n }, () =>
new Array(n).fill(false),
)
for (const [u, v] of edges) reach[u][v] = truefor (let k = 0; k < n; k++)
for (let i = 0; i < n; i++)
for (let j = 0; j < n; j++)
if (reach[i][k] && reach[k][j]) reach[i][j] = truereturn reach.some((row, i) => row[i])
}
// An undirected graph with c components is a forest exactly when it// has n - c edges.function bruteForest(n: number, edges: Edge[]): boolean {
const adj = buildAdj(n, edges)
const seen = new Array(n).fill(false)
let comps = 0for (let s = 0; s < n; s++) {
if (seen[s]) continue
comps++
bfs(adj, s).forEach((d, v) => {
if (d >= 0) seen[v] = true
})
}
return edges.length === n - comps
}
A forest check by counting components
ts
test('iterative DFS visits in the recursive order', () => {
const rand = mulberry32(11)
for (let t = 0; t < 1000; t++) {
const n = 1 + Math.floor(rand() * 8)
const m = Math.floor(rand() * 14)
const adj = buildAdj(n, randomEdges(rand, n, m), true)
assert.deepEqual(dfs(adj, 0), dfsRec(adj, 0))
}
})
test('directed cycle test matches brute force', () => {
const rand = mulberry32(12)
for (let t = 0; t < 2000; t++) {
const n = 1 + Math.floor(rand() * 7)
const edges = randomEdges(rand, n, Math.floor(rand() * 10))
const adj = buildAdj(n, edges, true)
assert.equal(hasCycle(adj), bruteCycle(n, edges))
}
})
test('undirected cycle test matches the forest count', () => {
const rand = mulberry32(13)
for (let t = 0; t < 2000; t++) {
const n = 1 + Math.floor(rand() * 7)
const edges = randomEdges(rand, n, Math.floor(rand() * 8))
assert.equal(hasCycleUndirected(n, edges), !bruteForest(n, edges))
}
})
dfs.test.ts: 1,000 and 2,000 random graphs
text
✔ iterative DFS visits in the recursive order (11.0583ms)
✔ directed cycle test matches brute force (12.0175ms)
✔ undirected cycle test matches the forest count (12.5989ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0
Output of one run; the millisecond figures vary
Why is a "seen" flag enough for BFS and undirected search but not for directed cycle detection?
A directed edge to a seen node may lead to a finished one, as in a diamond, and that is not a cycle. Only an edge to an open node is.
What does a frame in the explicit stack hold, and what does popping one mean?
The node and the index of its next neighbour. Popping it means every neighbour has been tried: the recursive call would return.
Why does the undirected test skip an edge by its position and not by its other end?
Skipping by the other end would also skip a second, parallel edge to the parent, which is a real cycle of two edges.
Part 3 · Fewest transfers between metro stations
The problem
A metro has several lines, each a list of station numbers. You start at one station and want to reach another, and every time you change lines counts as a transfer. Return the fewest transfers, or -1 when no route exists. A start equal to the destination needs none.
The tempting model makes each station a node. That fails because riding five stops on one line costs nothing, while changing lines costs one, so edges between neighbouring stations carry different prices and plain BFS no longer applies.
Make each line a node instead. Two lines are neighbours when they share a station. Boarding a line is one step, so the number of lines boarded is a hop count, and BFS over lines gives the fewest boardings. Transfers are boardings minus one.
To build the graph without comparing every pair of lines, first make a map from station to the lines that stop there. Then expanding a line means walking its stations and, for each one, queuing the lines the map lists that have not been boarded yet.
Model
A node is
One step is
BFS distance counts
Stations
a station
one stop on a line
stops, not transfers
Lines
a line
boarding another line at a shared station
lines boarded
Stations
A node isa station
One step isone stop on a line
BFS distance countsstops, not transfers
Lines
A node isa line
One step isboarding another line at a shared station
BFS distance countslines boarded
Let S be the total number of station entries over all lines and L the number of lines. Building the map reads each entry once. Each line is queued at most once and walks its own stations once, and each station is expanded at most once, looking at the lines that serve it. So the time and the memory are both proportional to S plus L, however the lines overlap.
If the ride between stations had different costs, say a slow line and a fast one, the steps would carry weights and plain BFS would no longer be enough. The weighted shortest paths chapter handles that case.
The code
ts
exportfunction fewestTransfers(
lines: number[][],
from: number,
to: number,
): number {
if (from === to) return0const linesAt = new Map<number, number[]>()
lines.forEach((stops, id) => {
for (const s of stops) {
if (!linesAt.has(s)) linesAt.set(s, [])
linesAt.get(s)!.push(id)
}
})
if (!linesAt.has(from) || !linesAt.has(to)) return -1
metro.ts: map each station to the lines that stop there
ts
const boarded: number[] = new Array(lines.length).fill(-1)
const queue: number[] = []
for (const l of linesAt.get(from)!) {
boarded[l] = 1
queue.push(l)
}
const expanded = new Set<number>()
for (let head = 0; head < queue.length; head++) {
const l = queue[head]
for (const s of lines[l]) {
if (s === to) return boarded[l] - 1if (expanded.has(s)) continue
expanded.add(s)
for (const next of linesAt.get(s)!) {
if (boarded[next] === -1) {
boarded[next] = boarded[l] + 1
queue.push(next)
}
}
}
}
return -1
}
metro.ts, continued: BFS over lines
One detail keeps the work small. A set of expanded stations makes sure each station is expanded once, however many lines pass through it. Without it a busy interchange would be re-expanded for every line that stops there.
The answer is returned when the line being expanded contains the destination. Lines leave the queue in order of boardings, so the first line found that contains the destination has the fewest.
ts
import { fewestTransfers } from'./metro.ts'// Stations are numbered; each inner array is one line.const lines = [[0, 1, 2, 3], [3, 4, 5], [5, 6, 7], [2, 8], [9, 10]]
console.log('0 to 7:', fewestTransfers(lines, 0, 7))
console.log('1 to 8:', fewestTransfers(lines, 1, 8))
console.log('0 to 10:', fewestTransfers(lines, 0, 10))
console.log('4 to 4:', fewestTransfers(lines, 4, 4))
Five lines over eleven stations
text
0 to 7: 21 to 8: 10 to 10: -14 to 4: 0
Output of one run
Station 0 to 7 needs the first line, the second at station 3 and the third at station 5, which is two transfers. Station 1 to 8 changes once, at station 2. Station 10 sits on a line that touches no other, so station 0 cannot reach it. Related on LeetCode: Bus Routes.
Testing it
The check uses a different idea. Start with the set of stations reachable on zero boardings, add every station on any line that touches the set, and count how many rounds pass before the destination appears.
ts
// Grow the set of reachable stations one boarding at a time.function brute(lines: number[][], from: number, to: number): number {
if (from === to) return0let reach = new Set([from])
for (let boardings = 1; ; boardings++) {
const next = new Set(reach)
for (const stops of lines) {
if (stops.some((s) => reach.has(s))) {
stops.forEach((s) => next.add(s))
}
}
if (next.has(to)) return boardings - 1if (next.size === reach.size) return -1
reach = next
}
}
The edge cases cover an empty network, start equal to destination, a destination on another island, a line listing a station twice, and a station that no line serves. The random networks have up to five lines of up to four stations over nine station numbers, so many have no route at all.
Why is plain BFS over stations the wrong model here?
Staying on a line is free and changing lines costs one. BFS counts every edge as one, so it would count stops and not transfers.
What does the set of expanded stations prevent?
Re-walking an interchange once for every line that passes through it, which would repeat the same work.
What does the function return when the start and destination are the same station, even one no line serves?
0. The first check returns before any line is looked at.
Part 4 · Copying an org chart graph
The problem
A company stores who reports to whom as linked objects. Each person has a name and an array of direct reports, and because of dotted-line arrangements the links may loop back, so the structure is a graph and not a tree. The task is a complete copy that shares no object with the original.
A recursive copy that makes a new person for every link breaks twice. A loop makes it run forever, and a person with two managers gets copied twice, so the copy has two people where the original has one. Both problems have one cure: a Map from each original person to its copy, consulted before any copy is made.
Any traversal order would do. A BFS with a queue avoids recursion, and the map doubles as the seen set. When a person is first met, create the copy and queue the original. Whether or not the person is new, add the link from the current copy to the report's copy.
ts
exportclass Person {
name: string
reports: Person[]
constructor(name: string) {
this.name = name
this.reports = []
}
}
// Deep copy of everything reachable from `start`, cycles included.exportfunction cloneChart(start: Person | null): Person | null {
if (start === null) returnnullconst copy = new Map<Person, Person>()
copy.set(start, new Person(start.name))
const queue: Person[] = [start]
for (let head = 0; head < queue.length; head++) {
const p = queue[head]
for (const r of p.reports) {
if (!copy.has(r)) {
copy.set(r, new Person(r.name))
queue.push(r)
}
copy.get(p)!.reports.push(copy.get(r)!)
}
}
return copy.get(start)!
}
clone.ts: the Person class and the copy
A shallow copy of a person copies the reports array but leaves every entry pointing at the original people, so changing a copy would change the original. A deep copy makes new people all the way down. Only the deep copy meets the requirement here. JavaScript has a built-in, structuredClone, and it does keep loops, but it returns plain objects without the class, as a short run shows.
ts
const boss = new Person('Asha')
const lead = new Person('Ravi')
boss.reports.push(lead)
lead.reports.push(boss) // a loop back to the topconst copy = structuredClone(boss)
console.log('loop kept:', copy.reports[0].reports[0] === copy)
console.log('same object:', copy === boss)
console.log('still a Person:', copy instanceof Person)
The built-in structuredClone on a loop of two people
text
loop kept: true
same object: false
still a Person: false
Output of one run
The loop survives and the copy is a different object, but instanceof Person is false, so any method on the class would be missing. Writing the copy by hand keeps the class and shows the technique, which also applies to structures the built-in cannot copy.
Each person is queued once, and each entry in a reports array is copied once, so the time is proportional to the people plus the links. The map holds one entry per person. A recursive copy has the same cost but would need one call frame per level of the longest chain, which is the limit met in the depth-first search lesson.
Checking the copy
The copy must keep
How the code keeps it
every person exactly once
the map is checked before a person is created
every link, including repeats
a link is added on every visit to a report entry
loops and self-reports
the copy of a person already in the map is reused
independence from the original
only new Person objects are ever linked
Adding the link on every visit, not only the first, is what preserves a repeated link and a link back to an ancestor. The copy is checked by listing everybody in both graphs in the same BFS order, then comparing names, link counts and link targets by position, and finally checking that no object in the copy is also in the original.
ts
function everyone(start: Person): Person[] {
const seen = new Set([start])
const list = [start]
for (let head = 0; head < list.length; head++) {
for (const r of list[head].reports) {
if (!seen.has(r)) {
seen.add(r)
list.push(r)
}
}
}
return list
}
Listing everyone reachable
ts
// Same names and same links, and no object shared with the original.function sameShapeNoSharing(a: Person, b: Person): boolean {
const xs = everyone(a)
const ys = everyone(b)
if (xs.length !== ys.length) returnfalseconst index = new Map(xs.map((p, i) => [p, i]))
const yIndex = new Map(ys.map((p, i) => [p, i]))
if (ys.some((p) => index.has(p))) returnfalsereturn xs.every((p, i) => {
const q = ys[i]
return (
p.name === q.name &&
p.reports.length === q.reports.length &&
p.reports.every(
(r, k) => index.get(r) === yIndex.get(q.reports[k]),
)
)
})
}
Comparing two charts
ts
type Link = [number, number]
function chart(names: string[], links: Link[]): Person[] {
const people = names.map((n) => new Person(n))
for (const [a, b] of links) people[a].reports.push(people[b])
return people
}
test('null, one person, and a person who reports to themselves', () => {
assert.equal(cloneChart(null), null)
const [solo] = chart(['Asha'], [])
assert.ok(sameShapeNoSharing(solo, cloneChart(solo)!))
const [loop] = chart(['Ravi'], [[0, 0]])
const copy = cloneChart(loop)!
assert.equal(copy.reports[0], copy)
assert.notEqual(copy, loop)
})
test('a chart with a cycle and a repeated link', () => {
const links: Link[] = [[0, 1], [0, 2], [1, 3], [2, 3], [3, 0], [0, 1]]
const people = chart(['Asha', 'Ravi', 'Meena', 'Kiran'], links)
assert.ok(sameShapeNoSharing(people[0], cloneChart(people[0])!))
})
test('a chain of 100,000 people', () => {
const people = chart(
Array.from({ length: 100_000 }, (_, i) => 'p' + i),
Array.from({ length: 99_999 }, (_, i): Link => [i, i + 1]),
)
assert.equal(everyone(cloneChart(people[0])!).length, 100_000)
})
clone.test.ts: null, a self-report, a cycle and a long chain
text
✔ null, one person, and a person who reports to themselves (1.0615ms)
✔ a chart with a cycle and a repeated link (0.2255ms)
✔ a chain of 100,000 people (122.1445ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0
Output of one run; the millisecond figures vary
Note that assert.equal from node:assert/strict compares objects by identity, so assert.equal(copy.reports[0], copy) asks whether the report is the very same object as the copy, which is what a self-report must be. The chain of 1,00,000 people would overflow a recursive copy, and the queue handles it without trouble. Related on LeetCode: Clone Graph.
Why is the map consulted before a copy is made?
It stops a loop from copying forever and makes a person with two managers one copy, not two.
Why is the link added on every visit and not only when the person is new?
Each entry in a reports array is a separate link. Skipping it for an already copied person would lose links, including the one back to an ancestor.
What does cloneChart(null) return?
null. The first line handles an empty chart before anything is copied.
Part 5 · The person everyone trusts
The problem
In a group of n people, numbered 0 to n - 1, some trust others. A pair [a, b] means a trusts b. A judge is a person who trusts nobody and is trusted by every other person. Find the judge, or return -1.
As a graph, each pair is a directed edge from a to b. The judge has out-degree 0 and in-degree n - 1. Counting both for everyone takes one pass over the pairs, and one pass over the people finds the match.
There is never more than one judge. If p and q were both judges, q would have to trust p because p is trusted by everyone else, but q trusts nobody. So the answer is one person or none, and the brute-force check below asserts that on every random input.
Two details need a decision. A pair that appears twice must count once, or three copies of one pair would give its target an in-degree of 3 and fool the check. A pair [a, a] says nothing useful, so it is ignored.
The code
ts
// trust[i] = [a, b] means person a trusts person b. The judge trusts// nobody and is trusted by everyone else. Returns that person or -1.type Pair = [number, number]
exportfunction findJudge(n: number, trust: Pair[]): number {
const seen = new Set<number>()
const trusts: number[] = new Array(n).fill(0)
const trustedBy: number[] = new Array(n).fill(0)
const ok = (x: number) => Number.isInteger(x) && x >= 0 && x < n
for (const [a, b] of trust) {
if (!(ok(a) && ok(b))) {
thrownew RangeError(`pair ${a},${b} is outside 0..${n - 1}`)
}
if (a === b || seen.has(a * n + b)) continue
seen.add(a * n + b)
trusts[a]++
trustedBy[b]++
}
for (let p = 0; p < n; p++) {
if (trusts[p] === 0 && trustedBy[p] === n - 1) return p
}
return -1
}
judge.ts: in-degree and out-degree counts
A set of keys a * n + b removes repeated pairs. Because a and b are whole numbers below n, each pair has its own key, as long as n * n stays below 2^53, which holds for n up to about 9.4 crore. A fractional or out-of-range number is rejected. The set can hold one key per distinct pair, so memory grows with the number of pairs, and the time is one pass over the pairs plus one pass over the people.
Everything here is counting, so no search is needed. When the question is about degrees (who has none, who has all), compute degrees first and see whether the answer falls out before reaching for BFS or DFS.
ts
import { findJudge } from'./judge.ts'
console.log(findJudge(4, [[0, 3], [1, 3], [2, 3], [0, 1]]))
console.log(findJudge(4, [[0, 3], [1, 3], [2, 3], [3, 0]]))
console.log(findJudge(4, [[0, 3], [1, 3]]))
// Three copies of one pair would fool a plain count for person 3.
console.log(findJudge(4, [[0, 3], [0, 3], [0, 3]]))
Four groups of four people
text
3
-1
-1
-1
Output of one run
The first group has judge 3. In the second, 3 trusts 0, so nobody qualifies. In the third, 3 is trusted by only two of the other three. In the fourth, a repeated pair would have made 3 look trusted by three people when it is trusted by one.
A shortcut you may meet is to compute in-degree minus out-degree and look for n - 1. It works only because pairs are distinct and self-pairs are dropped: then the in-degree is at most n - 1, so a score of n - 1 forces out-degree 0. With repeated pairs it gives wrong answers, which is why the code above removes them first.
A neighbouring question: the hub of a star
A relative of the judge problem is the star network. In it every link touches one hub station. Any two links therefore share exactly that hub, so the hub is the one station that appears in both of the first two links. Reading two links is enough, with no counting.
ts
type Pair = [number, number]
// In a star network every link touches the hub, so the hub is the one// station shared by any two links.exportfunction hub(links: Pair[]): number {
if (links.length < 2) thrownew RangeError('need at least two links')
const [a, b] = links[0]
const [c, d] = links[1]
return a === c || a === d ? a : b
}
star.ts: the hub of a star network
ts
// Same answer from degree counts.function hubByDegree(links: Pair[]): number {
const degree = new Map<number, number>()
for (const [a, b] of links) {
degree.set(a, (degree.get(a) ?? 0) + 1)
degree.set(b, (degree.get(b) ?? 0) + 1)
}
for (const [station, d] of degree) {
if (d === links.length) return station
}
return -1
}
const star: Pair[] = [[4, 7], [2, 7], [7, 9], [1, 7], [7, 5]]
console.log(hub(star), hubByDegree(star))
const two: Pair[] = [[3, 8], [8, 5]]
console.log(hub(two), hubByDegree(two))
The hub again from degree counts, on two small stars
text
7788
Output of one run
Both methods agree. The shortcut needs the input to be a real star: with two links that share no station, or the same link twice, the answer is not defined, and the function does not check for that.
Testing it
The check builds a full matrix of who trusts whom and tests every person against its definition, which shares nothing with the degree counts.
ts
function brute(n: number, trust: [number, number][]): number {
const t = Array.from({ length: n }, () => new Array(n).fill(false))
for (const [a, b] of trust) if (a !== b) t[a][b] = trueconst judges: number[] = []
for (let p = 0; p < n; p++) {
let ok = truefor (let q = 0; q < n; q++) {
if (t[p][q]) ok = falseif (q !== p && !t[q][p]) ok = false
}
if (ok) judges.push(p)
}
assert.ok(judges.length <= 1)
return judges.length === 1 ? judges[0] : -1
}
A matrix check that also asserts at most one judge
ts
test('edge cases', () => {
assert.equal(findJudge(0, []), -1)
assert.equal(findJudge(1, []), 0)
assert.equal(findJudge(1, [[0, 0]]), 0)
assert.equal(findJudge(2, [[1, 0]]), 0)
assert.equal(findJudge(4, [[0, 1], [0, 1], [2, 1], [3, 1]]), 1)
assert.equal(findJudge(4, [[0, 1], [2, 1], [3, 1], [1, 0]]), -1)
assert.throws(() => findJudge(2, [[0, 2]]), RangeError)
assert.throws(() => findJudge(3, [[0.5, 1]]), RangeError)
})
test('matches the matrix check, and never finds two judges', () => {
const rand = mulberry32(31)
for (let t = 0; t < 3000; t++) {
const n = Math.floor(rand() * 6)
const trust: [number, number][] = []
for (let k = Math.floor(rand() * 14); n > 0 && k > 0; k--) {
trust.push([Math.floor(rand() * n), Math.floor(rand() * n)])
}
assert.equal(findJudge(n, trust), brute(n, trust))
}
})
judge.test.ts
text
✔ edge cases (1.2398ms)
✔ matches the matrix check, and never finds two judges (13.944ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0
Output of one run; the millisecond figures vary
Edge cases include no people (nobody to be the judge, so -1), one person (trivially trusted by all of the zero others and trusting nobody, so 0), a person trusting themselves, a repeated pair, and a pair outside the range. Related on LeetCode: Find the Town Judge, Find Center of Star Graph.
Why can there be at most one judge?
A second judge would be trusted by the first, but a judge trusts nobody.
What does findJudge(1, []) return, and why?
0. The one person trusts nobody and is trusted by all n - 1 = 0 others.
Why are repeated pairs removed before counting?
Otherwise three copies of one pair give its target an in-degree of 3, which can look like trust from everyone.
Part 6 · Two teams with no rivals together
The problem
A coach must split people into two teams, and some pairs are rivals who may not share a team. Return a team for every person, or say it cannot be done. Draw rivalries as undirected edges: the task is to colour the nodes with two colours so every edge joins different colours. A graph that can be coloured this way is bipartite.
The method is BFS with colours. Colour the start 0. Every neighbour of a colour-0 node must be 1, and every neighbour of a colour-1 node must be 0. When BFS meets a neighbour that already has a colour, either it differs from the current node's colour, which is fine, or it matches, which is a clash.
The graph may be in several pieces, so the outer loop starts a fresh BFS from each node with no colour yet. Each piece can be coloured independently.
ts
import { buildAdj } from'./lib.ts'importtype { Edge } from'./lib.ts'// Side (0 or 1) for every person so that no rivals share a side,// or null when that is impossible.exportfunction twoTeams(n: number, rivals: Edge[]): number[] | null {
const adj = buildAdj(n, rivals)
const side: number[] = new Array(n).fill(-1)
for (let s = 0; s < n; s++) {
if (side[s] !== -1) continue
side[s] = 0const queue = [s]
for (let head = 0; head < queue.length; head++) {
const u = queue[head]
for (const v of adj[u]) {
if (side[v] === -1) {
side[v] = 1 - side[u]
queue.push(v)
} elseif (side[v] === side[u]) {
returnnull
}
}
}
}
return side
}
teams.ts: two-colouring by BFS
Why a clash proves it is impossible
In an undirected BFS, every edge joins two nodes whose levels differ by at most 1, where the level is the hop count from the start of that piece. The colour is the parity of the level, so a clash means both ends are on the same level.
Follow the BFS tree upward from both ends until the paths meet, at a node k levels above. That is k edges on each side, plus the clashing edge: a cycle of length 2k + 1. An odd cycle cannot be coloured with two colours, because colours would have to alternate around it and an odd count of alternations ends on the wrong colour. So a clash proves no split exists.
That argument also tells you how to report a failing pair. When the clash is found, the two ends and the BFS tree above them are the evidence, and you could return the odd cycle if the task asked for it.
If BFS finishes without a clash, every edge joins different parities, and the colouring is a valid split. A graph is therefore bipartite exactly when it has no odd cycle.
Animated sceneA ring of five forces a clash0:26
Watch for two rivals landing on the same team
Read it as steps
two rivals end up on one team
The ring of five shows it. A gets team one, its neighbours get team two, their other neighbours get team one, and then those two meet along the edge C to D.
Term
Meaning
bipartite
the nodes can be split into two groups with every edge joining the groups
level
the hop count from the start of the search
odd cycle
a cycle with an odd number of edges
piece (component)
a set of nodes that can reach one another
Running it
ts
import { twoTeams } from'./teams.ts'const ring6: [number, number][] = [
[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0],
]
const even = twoTeams(6, ring6)
const odd = twoTeams(5, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 0]])
const apart = twoTeams(6, [[0, 1], [1, 2], [3, 4]])
console.log('six in a ring: ', even)
console.log('five in a ring:', odd)
console.log('two groups and a loner:', apart)
A ring of six, a ring of five, and a graph in pieces
text
six in a ring: [ 0, 1, 0, 1, 0, 1 ]
five in a ring: null
two groups and a loner: [ 0, 1, 0, 0, 1, 0 ]
Output of one run
The time is proportional to the people plus the rivalries, because every edge is looked at from both ends and every node is queued once. The colours also serve as the seen marks, so no second array is needed.
The ring of six splits alternately. The ring of five returns null. The third graph has a path of three, a pair and a loner, and each piece is coloured on its own; the loner gets 0 by default.
The check tries every one of the 2^n ways to split n people into two sides, for n up to 7, and also verifies that every returned colouring separates all rivals.
ts
// Try every way to split n people into two sides.function splitExists(n: number, rivals: Edge[]): boolean {
for (let mask = 0; mask < 1 << n; mask++) {
const side = (p: number) => (mask >> p) & 1if (rivals.every(([a, b]) => side(a) !== side(b))) returntrue
}
returnfalse
}
✔ edge cases (1.7512ms)
✔ agrees with trying every split (11.4063ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0
Output of one run; the millisecond figures vary
A self-rivalry [0, 0] makes the task impossible, since the node meets itself with its own colour. A repeated rivalry changes nothing. Related on LeetCode: Is Graph Bipartite?, Possible Bipartition.
What does the function return for five people whose rivalries form one ring, and why?
null. The ring is a cycle of length 5, an odd cycle, so two colours cannot alternate around it.
Why does the outer loop start a new BFS from uncoloured nodes?
A graph may be in several pieces, and BFS from one node only reaches its own piece.
What does a self-rivalry do?
It makes a split impossible: the person is a neighbour of themselves and always has the same colour as themselves.
Part 7 · Turning one-way roads toward the capital
The problem
A region has n cities, numbered 0 to n - 1, with city 0 as the capital, and n - 1 one-way roads. A road [a, b] leads from a to b. If you ignore the directions, the roads connect every city without any loop, so they form a tree. Count the fewest roads to reverse so that every city can drive to the capital.
In a tree there is exactly one route between two cities, ignoring directions. So there is nothing to choose: every road on a city's route to the capital must point toward the capital, and a road that points away must be reversed. The answer is the number of roads that point away from city 0.
To count them, search outward from city 0. When the search walks a road in the direction it points, it is walking away from the capital, so that road must be reversed and counts 1. When the search walks it against its direction, the road already points home and counts 0. Each adjacency entry stores the neighbour and that cost.
ts
// roads[i] = [a, b] is a one-way road from city a to city b. Ignoring// directions the roads must form a tree. Returns how many roads to// reverse so every city can reach city 0.exportfunction roadsToReverse(n: number, roads: Edge[]): number {
if (n === 0 || roads.length !== n - 1) {
thrownew RangeError('not a tree')
}
const adj: [number, number][][] = Array.from({ length: n }, () => [])
for (const [a, b] of roads) {
if (!(a >= 0 && a < n && b >= 0 && b < n)) {
thrownew RangeError(`road ${a},${b} is outside 0..${n - 1}`)
}
adj[a].push([b, 1]) // leaving a for b: the road points away from 0
adj[b].push([a, 0]) // arriving at b: it already points toward 0
}
roads.ts: check the input and build the adjacency lists
ts
const seen: boolean[] = new Array(n).fill(false)
seen[0] = trueconst stack = [0]
let reached = 1let reversals = 0while (stack.length > 0) {
const u = stack.pop()!
for (const [v, away] of adj[u]) {
if (seen[v]) continue
seen[v] = true
reached++
reversals += away
stack.push(v)
}
}
if (reached !== n) thrownew RangeError('not a tree')
return reversals
}
roads.ts, continued: a search from the capital with a stack
The search could be a BFS just as well, because only the cost of each edge matters and the order of visits does not. The explicit stack is used here for another reason: a country with a long chain of cities would overflow a recursive search, and this version has no such limit.
Why it is a tree, and testing it
The code first checks that the input is a tree, because the argument above depends on it. A connected graph needs at least n - 1 edges. If it has exactly n - 1 and is connected, it has no cycle: a cycle would let you remove an edge and stay connected with fewer than n - 1. So the check is: n - 1 roads, and the search reaches all n cities. Anything else throws.
Each city is reached by exactly one road in a tree, so marking a city when it is pushed is safe. The search uses a plain stack of cities, and that also means a chain of 2,00,000 cities causes no trouble.
a connected graph with no cycle; n nodes have n - 1 edges
route
the one path between two nodes of a tree
reversal
swapping the two ends of a road so it points the other way
Seven cities have six roads. The road from 1 to 3 points away from city 0, and so does the road from 5 to 6, which gives 2. The roads 2 to 0, 1 to 2, 4 to 3 and 5 to 4 already lead toward the capital.
The check tries every subset of roads to reverse, keeps the subsets that let every city reach city 0, and takes the smallest. That is 2^(n - 1) subsets for n up to 8.
ts
// Try every subset of roads to reverse; keep the smallest that works.function brute(n: number, roads: Edge[]): number {
let best = Infinity
for (let mask = 0; mask < 1 << roads.length; mask++) {
const into: number[][] = Array.from({ length: n }, () => [])
roads.forEach(([a, b], i) => {
if ((mask >> i) & 1) into[a].push(b)
else into[b].push(a)
})
// Walk backwards along roads from city 0: who can reach it?const seen = new Set([0])
const todo = [0]
for (let h = 0; h < todo.length; h++) {
for (const v of into[todo[h]]) {
if (!seen.has(v)) {
seen.add(v)
todo.push(v)
}
}
}
if (seen.size === n) {
best = Math.min(best, mask.toString(2).split('1').length - 1)
}
}
return best
}
A tree has one route between two cities, so each road's needed direction is decided by which side of it the capital is on.
What does the function do for one city and no roads?
Returns 0: the only city is the capital and nothing needs reversing.
How does the code tell that the roads are not a tree?
The count of roads is not n - 1, or the search from city 0 does not reach all n cities.
Part 8 · The longest loop of referrals
The problem
Each person in a company refers at most one other person to a programme. A loop of referrals is a chain that comes back to its start. Given next[i], the person i refers, or -1 for nobody, find the number of people on the longest loop, or -1 if there is no loop.
Each node has at most one outgoing edge, so the graph is a set of chains that either end at -1 or run into a loop. A walk from any node has one road to follow, which makes a search simple: just walk.
Walk from each node that no earlier walk has touched. Stamp every node with the walk that first reached it and its position in that walk. If the walk stops at a node stamped by this same walk, it has gone around a loop, and the loop has steps - position nodes. If it stops at -1 or at a node stamped by an earlier walk, it found nothing new: an earlier walk has already counted any loop beyond that node.
ts
// next[i] is the person i refers, or -1 for nobody. Returns the number// of people on the longest loop of referrals, or -1 when there is none.exportfunction longestLoop(next: number[]): number {
const n = next.length
for (const x of next) {
if (!(x === -1 || (Number.isInteger(x) && x >= 0 && x < n))) {
thrownew RangeError(`bad referral ${x}`)
}
}
// Per node: the walk that first met it, and its place in that walk.const walk: number[] = new Array(n).fill(-1)
const step: number[] = new Array(n).fill(0)
let best = -1for (let s = 0; s < n; s++) {
if (walk[s] !== -1) continuelet u = s
let k = 0while (u !== -1 && walk[u] === -1) {
walk[u] = s
step[u] = k++
u = next[u]
}
if (u !== -1 && walk[u] === s) best = Math.max(best, k - step[u])
}
return best
}
loops.ts: walks with stamps
Term
Meaning
walk
following the referrals from a start person until the chain ends or a person repeats
stamp
a mark on a person recording which walk reached it first, and at which step
loop
a chain of referrals that returns to its first person
The code starts by rejecting any referral outside -1 to n - 1, because a bad index would make the walk read past the array and return a wrong answer instead of failing.
Cost and checks
Every node is stamped once, and a walk never moves onto a stamped node except to stop. The total work is therefore O(n), and no node is walked from more than once.
ts
import { longestLoop } from'./loops.ts'// Person 0 refers 1, 1 refers 2, 2 refers 0 (a loop of 3); 3 refers 0;// 4 and 5 refer each other; 6 refers nobody.const next = [1, 2, 0, 0, 5, 4, -1]
console.log('longest loop:', longestLoop(next))
console.log('no loop:', longestLoop([1, 2, 3, -1]))
A loop of three, a tail, a loop of two, and no loop
text
longest loop: 3
no loop: -1
Output of one run
ts
// longestLoop with a printout of every walk.function traced(next: number[]): void {
const walk: number[] = new Array(next.length).fill(-1)
const step: number[] = new Array(next.length).fill(0)
for (let s = 0; s < next.length; s++) {
if (walk[s] !== -1) {
console.log(`start ${s}: already stamped, skipped`)
continue
}
const path: number[] = []
let u = s
while (u !== -1 && walk[u] === -1) {
walk[u] = s
step[u] = path.length
path.push(u)
u = next[u]
}
const loop = u !== -1 && walk[u] === s
const size = loop ? path.length - step[u] : 0const end = loop ? `back to ${u}, loop of ${size}` : 'no new loop'
console.log(`start ${s}: ${path.join(' ')} then ${end}`)
}
}
traced([1, 2, 0, 0, 5, 4, -1])
The same walks, printed
text
start 0: 012 then back to 0, loop of 3
start 1: already stamped, skipped
start 2: already stamped, skipped
start 3: 3 then no new loop
start 4: 45 then back to 4, loop of 2
start 5: already stamped, skipped
start 6: 6 then no new loop
Output of one run
Read the trace in order. The walk from 0 visits 0, 1 and 2 and returns to 0, so it found a loop of three. Starts 1 and 2 are skipped, since they were stamped. The walk from 3 stops at once because person 0 was stamped by an earlier walk. The walk from 4 finds the loop of two.
The loop 0, 1, 2 has three people, person 3 leads into it, 4 and 5 refer each other for a loop of two, and 6 refers nobody. The answer is 3.
The check starts from every person separately and follows referrals with a map of positions until a node repeats or the chain ends. It does not share the stamping idea.
ts
// From every start, walk until a node repeats or the chain ends.function brute(next: number[]): number {
let best = -1for (let s = 0; s < next.length; s++) {
const at = new Map<number, number>()
let u = s
let k = 0while (u !== -1 && !at.has(u)) {
at.set(u, k++)
u = next[u]
}
if (u !== -1) best = Math.max(best, k - at.get(u)!)
}
return best
}
A separate walk from every person
ts
test('edge cases', () => {
assert.equal(longestLoop([]), -1)
assert.equal(longestLoop([-1]), -1)
assert.equal(longestLoop([0]), 1)
assert.equal(longestLoop([1, 2, -1]), -1)
assert.equal(longestLoop([1, 0, 3, 4, 2]), 3)
assert.throws(() => longestLoop([5]), RangeError)
})
test('matches the repeat-seeking walk on random inputs', () => {
const rand = mulberry32(61)
for (let t = 0; t < 3000; t++) {
const n = Math.floor(rand() * 9)
const next = Array.from({ length: n }, () => {
const x = Math.floor(rand() * (n + 2))
return x >= n ? -1 : x
})
assert.equal(longestLoop(next), brute(next))
}
})
test('one loop of 300,000 people', () => {
const n = 300_000
const next = Array.from({ length: n }, (_, i) => (i + 1) % n)
assert.equal(longestLoop(next), n)
})
loops.test.ts: edge cases, random lists and one long loop
text
✔ edge cases (1.2825ms)
✔ matches the repeat-seeking walk on random inputs (8.5114ms)
✔ one loop of 300,000 people (38.3683ms)
ℹ tests 3
ℹ pass 3
ℹ fail 0
Output of one run; the millisecond figures vary
A person who refers themselves is a loop of one, and the code reports it. A value outside -1 to n - 1 throws. Another problem in this family asks for every path from one node to another in a graph with no cycles. That is a DFS that records the path and prints it at the target, the same shape as the budget route search in the tree DFS chapter. Related on LeetCode: Longest Cycle in a Graph, All Paths From Source to Target.
Why does a walk that stops at a node stamped by an earlier walk add nothing?
Any loop reachable from that node was already found by the earlier walk, and this walk has no way into one that it has not seen.
What does longestLoop([0]) return?
1. A person who refers themselves is a loop of one person.
Why is the total work linear even though a walk is started from many nodes?
A walk starts only at an unstamped node and stamps every node it enters, so each node is stamped once in total.