Add graph-algorithms module: Dijkstra (heap, array, lazy deletion), Bellman-Ford reference, Kahn topological sort, Union-Find strategies, Kruskal and Prim (15 tests, 13 transcripts)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b3RckKrNbvvStS36UM
This commit is contained in:
2026-11-18 21:05:59 +05:30
co-authored by Claude Sonnet 5.5
parent eef175d669
commit 05f41a3ef7
30 changed files with 1490 additions and 0 deletions
+1
View File
@@ -26,6 +26,7 @@ One module per article. This repository currently holds:
| [`rate-limiter`](rate-limiter/) | Low-Level Design: Rate Limiter in Java (Token Bucket, Sliding Window) + Spring Boot | this commit | | [`rate-limiter`](rate-limiter/) | Low-Level Design: Rate Limiter in Java (Token Bucket, Sliding Window) + Spring Boot | this commit |
| [`bookmyshow`](bookmyshow/) | Low-Level Design: BookMyShow Seat Booking in Java (Handling Concurrent Bookings) | this commit | | [`bookmyshow`](bookmyshow/) | Low-Level Design: BookMyShow Seat Booking in Java (Handling Concurrent Bookings) | this commit |
| [`splitwise`](splitwise/) | Low-Level Design: Splitwise (Expense Sharing) in Java | this commit | | [`splitwise`](splitwise/) | Low-Level Design: Splitwise (Expense Sharing) in Java | this commit |
| [`graph-algorithms`](graph-algorithms/) | Graph Algorithms in Java: Dijkstra, Topological Sort and Union-Find | this commit |
## `collections` module ## `collections` module
+58
View File
@@ -0,0 +1,58 @@
# graph-algorithms
Companion code for the ankurm.com article **Graph Algorithms in Java: Dijkstra, Topological Sort and Union-Find**.
Dijkstra (heap, lazy deletion, array version), Bellman-Ford as the reference answer, Kahn's topological sort
(plus smallest-first, layered and recursive DFS variants), Union-Find with each optimisation switchable, and
Kruskal and Prim. Every figure and console line in the article is quoted from a file in `output/`, which the JUnit
tests write while asserting the same numbers. There is no `docs/` folder: the explanations live in the article itself.
## Versions
| Component | Version | Verified against |
|---|---|---|
| JDK | Temurin 25.0.5+8 (LTS) | `java -version`; Adoptium `available_lts_releases` |
| JUnit | 6.1.3 | `junit-bom` `maven-metadata.xml` on Maven Central (latest GA) |
| Maven | 3.9.x | `mvn -version` |
## Quickstart
```bash
cd graph-algorithms
export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH"
./scripts/run-all.sh # runs 15 tests and regenerates output/*.txt
```
The first Maven run must be online so the plugins land in the local cache.
## Source map
| File | What it holds |
|---|---|
| `Graph.java` | weighted directed adjacency list |
| `Dijkstra.java` | heap version with stats, `O(V^2)` array version, visited-set version, no-check demo |
| `BellmanFord.java` | the reference answer; correct with negative edges |
| `TopologicalSort.java` | `kahn`, `kahnSmallestFirst`, `kahnLevels`, recursive `dfs`, `isValidOrder` |
| `UnionFind.java` | four strategies (naive, by size, compression, both), hop counter, `maxDepth` |
| `SpanningTree.java` | `kruskal` and `prim` |
| `Pitfalls.java` | `int` infinity overflow and a Union-Find whose `union` skips `find` |
## Captured output
| File | What it shows |
|---|---|
| `01-dijkstra-trace.txt` | pop-by-pop trace on a 6-vertex graph, including two stale entries |
| `02-dijkstra-stale-entries.txt` | work with and without the stale-entry check |
| `03-dijkstra-vs-bellman-ford.txt` | 3000 seeded random graphs, 0 disagreements |
| `04-negative-edges.txt` | one negative edge: exception, visited-set version, lazy version, Bellman-Ford |
| `05-quadratic-vs-heap.txt` | work counts for the array and heap versions on a sparse and a dense graph |
| `06-kahn-course-schedule.txt` | course schedule, layers, and the cyclic-graph flag |
| `07-topological-random-agreement.txt` | Kahn and DFS vs a transitive-closure reference |
| `08-recursion-depth.txt` | recursive DFS overflows a 512 KB stack on a 100,000-vertex chain; Kahn does not |
| `09-union-find-chain.txt` | depth and hops for each Union-Find strategy |
| `10-union-find-random-agreement.txt` | all four strategies vs BFS component counts |
| `11-kruskal-prim.txt` | minimum spanning tree and a Kruskal/Prim cross-check |
| `12-pitfall-int-infinity.txt` | `Integer.MAX_VALUE + 5` makes an unreachable vertex look cheap |
| `13-pitfall-union-without-find.txt` | `parent[a] = b` loses a connection |
Operation counts are deterministic (seeded inputs); nothing in `output/` is a timing.
@@ -0,0 +1,29 @@
Dijkstra trace, classic 6-vertex graph, source A
================================================
pop 0 @0 settled
relax 0 -> 1 dist[1] = 7
relax 0 -> 2 dist[2] = 9
relax 0 -> 5 dist[5] = 14
pop 1 @7 settled
relax 1 -> 3 dist[3] = 22
pop 2 @9 settled
relax 2 -> 3 dist[3] = 20
relax 2 -> 5 dist[5] = 11
pop 5 @11 settled
relax 5 -> 4 dist[4] = 20
pop 5 @14 stale (best known is 11) -> skipped
pop 4 @20 settled
pop 3 @20 settled
pop 3 @22 stale (best known is 20) -> skipped
dist[A] = 0
dist[B] = 7
dist[C] = 9
dist[D] = 20
dist[E] = 20
dist[F] = 11
cheapest path to E: A -> C -> F -> E (cost 20)
stats: Stats[pushes=8, pops=8, stalePops=2, edgeScans=18, relaxations=7]
@@ -0,0 +1,7 @@
Lazy deletion: with and without the stale-entry check (seeded graph, V=2000, E=10000)
=====================================================================================
with check : Stats[pushes=2831, pops=2831, stalePops=849, edgeScans=9915, relaxations=2830]
without check : Stats[pushes=2831, pops=2831, stalePops=849, edgeScans=14168, relaxations=2830]
same distances: true
@@ -0,0 +1,6 @@
Dijkstra vs Bellman-Ford on seeded random graphs
================================================
cases checked : 3000
cases with an unreachable vertex: 2323
disagreements : 0
@@ -0,0 +1,7 @@
One negative edge: A->B 1, A->C 2, C->B -5
==========================================
Dijkstra.run(g, A) throws : Dijkstra needs non-negative weights; use Bellman-Ford instead
visited-set version, dist[B] : 1
lazy version, check removed, dist[B]: -3 (pops 4)
Bellman-Ford, dist[B] : -3
@@ -0,0 +1,9 @@
Array scan O(V^2) vs binary heap: work counted, not timed
=========================================================
sparse V=2000 E=8000:
array version : min-scan steps 3916000
heap version : pushes 2541, pops 2541, edge scans 7784
dense V=600 E=150000:
array version : min-scan steps 360000
heap version : pushes 2292, pops 2292, edge scans 150000
@@ -0,0 +1,12 @@
Kahn's algorithm on a 7-course prerequisite graph
=================================================
kahn (queue order) : Intro, Maths, DBMS, DSA, OS, Networks, Compilers acyclic=true
kahn (smallest first): Intro, Maths, DSA, DBMS, OS, Networks, Compilers acyclic=true
semester 1 : Intro, Maths
semester 2 : DSA, DBMS
semester 3 : OS
semester 4 : Networks, Compilers
cycle 1->2->1 plus 2->3, kahn returns: [0] acyclic=false
(vertex 0 is the only one that could be ordered; the flag is the only signal of the cycle)
@@ -0,0 +1,7 @@
Kahn and DFS vs a transitive-closure reference on seeded random graphs
======================================================================
cases checked : 3000
cases with a cycle : 2016
cases acyclic (orders valid): 984
disagreements : 0
@@ -0,0 +1,5 @@
A 100,000-vertex chain on a thread with a 512 KB stack
======================================================
recursive DFS : StackOverflowError
Kahn : ordered 100000 vertices, acyclic=true
@@ -0,0 +1,13 @@
union(0,1), union(1,2), ... union(n-2,n-1) with n=20000, then find(0) twice
===========================================================================
NAIVE max depth 19999 | find(0) #1: 19999 hops | find(0) #2: 19999 hops
BY_SIZE max depth 1 | find(0) #1: 1 hops | find(0) #2: 1 hops
COMPRESSION max depth 19999 | find(0) #1: 19999 hops | find(0) #2: 1 hops
BY_SIZE_AND_COMPRESSION max depth 1 | find(0) #1: 1 hops | find(0) #2: 1 hops
Tournament pattern, n=16384: round r joins sets of size 2^r, so equal sizes meet every time
NAIVE max depth 14
BY_SIZE max depth 14
COMPRESSION max depth 13
BY_SIZE_AND_COMPRESSION max depth 13
@@ -0,0 +1,6 @@
Union-Find (all four strategies) vs BFS component count
=======================================================
cases checked : 2000
strategies : [NAIVE, BY_SIZE, COMPRESSION, BY_SIZE_AND_COMPRESSION]
disagreements : 0
@@ -0,0 +1,14 @@
Minimum spanning tree of the classic 6-vertex graph
===================================================
Kruskal total weight: 33
C - F (2)
D - E (6)
A - B (7)
A - C (9)
E - F (9)
Prim total weight : 33
random graphs checked : 2000
of which disconnected : 1330
Kruskal/Prim disagreements : 0
@@ -0,0 +1,6 @@
Bellman-Ford with int infinity: 2 -> 3 is unreachable from 0
============================================================
Integer.MAX_VALUE + 5 = -2147483644
int version, dist[3] : -2147483644
long + check, dist[3] : unreachable (INF)
@@ -0,0 +1,5 @@
union(0,1) then union(0,2), then ask connected(0,1)
===================================================
buggy connected(0,1): false
correct connected(0,1): true
+64
View File
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm.interviewlab</groupId>
<artifactId>graph-algorithms</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>java-interview-lab :: graph-algorithms</name>
<description>
Runnable companion code for ankurm.com's "Graph Algorithms in Java" article: Dijkstra, Kahn's topological sort,
Union-Find, Kruskal and Prim, cross-checked against reference implementations, with captured transcripts.
</description>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>6.1.3</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<argLine>-Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Regenerates every file in output/. Needs JDK 25 and Maven. The first Maven run must be online.
# Every file is written by a JUnit test that asserts the same numbers it prints, so the figures
# in the article are assertions: they fail the build the moment they stop being true.
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p output
mvn -B -q -T1 test
echo "done:"; ls -1 output
@@ -0,0 +1,39 @@
package com.ankurm.interviewlab.graph;
import com.ankurm.interviewlab.graph.Graph.Edge;
import java.util.Arrays;
/** Bellman-Ford: slower than Dijkstra, but correct with negative edges. Used as the reference answer. */
public final class BellmanFord {
public record Result(long[] dist, boolean negativeCycle) { }
private BellmanFord() { }
public static Result run(Graph g, int source) {
int n = g.size();
long[] dist = new long[n];
Arrays.fill(dist, Dijkstra.INF);
dist[source] = 0;
for (int pass = 1; pass < n; pass++) {
boolean changed = false;
for (Edge e : g.edges()) {
if (dist[e.from()] != Dijkstra.INF && dist[e.from()] + e.weight() < dist[e.to()]) {
dist[e.to()] = dist[e.from()] + e.weight();
changed = true;
}
}
if (!changed) {
break;
}
}
boolean negativeCycle = false;
for (Edge e : g.edges()) {
if (dist[e.from()] != Dijkstra.INF && dist[e.from()] + e.weight() < dist[e.to()]) {
negativeCycle = true;
break;
}
}
return new Result(dist, negativeCycle);
}
}
@@ -0,0 +1,171 @@
package com.ankurm.interviewlab.graph;
import com.ankurm.interviewlab.graph.Graph.Edge;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.function.Consumer;
/** Dijkstra's single-source shortest paths with a binary heap and "lazy deletion". */
public final class Dijkstra {
/** Marks a vertex that has not been reached. Always test for it before adding a weight. */
public static final long INF = Long.MAX_VALUE;
/** What the run did. Handy for seeing why lazy deletion needs a stale-entry check. */
public record Stats(int pushes, int pops, int stalePops, int edgeScans, int relaxations) { }
public record Result(long[] dist, int[] parent, Stats stats) {
public boolean reachable(int v) {
return dist[v] != INF;
}
/** The vertices on a cheapest path from the source to {@code target}, or an empty list. */
public List<Integer> pathTo(int target) {
if (!reachable(target)) {
return List.of();
}
List<Integer> path = new ArrayList<>();
for (int v = target; v != -1; v = parent[v]) {
path.add(v);
}
Collections.reverse(path);
return path;
}
}
private record Entry(int node, long dist) { }
private Dijkstra() { }
public static Result run(Graph g, int source) {
return run(g, source, true, true, null);
}
public static Result run(Graph g, int source, boolean skipStale, Consumer<String> trace) {
return run(g, source, skipStale, true, trace);
}
/** Demo only: runs on a graph with negative edges instead of rejecting it. */
public static Result runWithoutNegativeCheck(Graph g, int source) {
return run(g, source, true, false, null);
}
private static Result run(Graph g, int source, boolean skipStale, boolean checkNegative, Consumer<String> trace) {
if (checkNegative && g.hasNegativeEdge()) {
throw new IllegalArgumentException("Dijkstra needs non-negative weights; use Bellman-Ford instead");
}
int n = g.size();
long[] dist = new long[n];
int[] parent = new int[n];
Arrays.fill(dist, INF);
Arrays.fill(parent, -1);
dist[source] = 0;
PriorityQueue<Entry> pq = new PriorityQueue<>(Comparator.comparingLong(Entry::dist));
pq.add(new Entry(source, 0));
int pushes = 1;
int pops = 0;
int stale = 0;
int scans = 0;
int relaxations = 0;
while (!pq.isEmpty()) {
Entry e = pq.poll();
pops++;
int u = e.node();
if (e.dist() > dist[u]) {
stale++;
if (trace != null) {
trace.accept("pop " + u + " @" + e.dist() + " stale (best known is " + dist[u] + ")"
+ (skipStale ? " -> skipped" : " -> expanded anyway"));
}
if (skipStale) {
continue;
}
} else if (trace != null) {
trace.accept("pop " + u + " @" + e.dist() + " settled");
}
for (Edge edge : g.from(u)) {
scans++;
long candidate = dist[u] + edge.weight();
if (candidate < dist[edge.to()]) {
dist[edge.to()] = candidate;
parent[edge.to()] = u;
pq.add(new Entry(edge.to(), candidate));
pushes++;
relaxations++;
if (trace != null) {
trace.accept(" relax " + u + " -> " + edge.to() + " dist[" + edge.to() + "] = " + candidate);
}
}
}
}
return new Result(dist, parent, new Stats(pushes, pops, stale, scans, relaxations));
}
/** What the array version did: no heap, one linear scan per settled vertex. */
public record QuadraticResult(long[] dist, long minScanSteps) { }
/** The textbook O(V^2) version with no heap: scan every vertex to find the closest unsettled one. */
public static QuadraticResult runQuadratic(Graph g, int source) {
int n = g.size();
long[] dist = new long[n];
boolean[] settled = new boolean[n];
Arrays.fill(dist, INF);
dist[source] = 0;
long steps = 0;
for (int round = 0; round < n; round++) {
int u = -1;
for (int v = 0; v < n; v++) {
steps++;
if (!settled[v] && dist[v] != INF && (u == -1 || dist[v] < dist[u])) {
u = v;
}
}
if (u == -1) {
break;
}
settled[u] = true;
for (Edge edge : g.from(u)) {
long candidate = dist[u] + edge.weight();
if (candidate < dist[edge.to()]) {
dist[edge.to()] = candidate;
}
}
}
return new QuadraticResult(dist, steps);
}
/**
* The version many tutorials write: a "visited" set instead of a stale-entry check. Correct for
* non-negative weights, wrong the moment a negative edge appears. Kept for the pitfalls demo.
*/
public static long[] runWithVisitedSet(Graph g, int source) {
int n = g.size();
long[] dist = new long[n];
boolean[] visited = new boolean[n];
Arrays.fill(dist, INF);
dist[source] = 0;
PriorityQueue<Entry> pq = new PriorityQueue<>(Comparator.comparingLong(Entry::dist));
pq.add(new Entry(source, 0));
while (!pq.isEmpty()) {
int u = pq.poll().node();
if (visited[u]) {
continue;
}
visited[u] = true;
for (Edge edge : g.from(u)) {
long candidate = dist[u] + edge.weight();
if (!visited[edge.to()] && candidate < dist[edge.to()]) {
dist[edge.to()] = candidate;
pq.add(new Entry(edge.to(), candidate));
}
}
}
return dist;
}
}
@@ -0,0 +1,59 @@
package com.ankurm.interviewlab.graph;
import java.util.ArrayList;
import java.util.List;
/**
* A weighted directed graph stored as an adjacency list: one list of outgoing edges per vertex.
* Vertices are the integers 0..n-1. An undirected edge is stored as two directed edges.
*/
public final class Graph {
/** One directed edge. */
public record Edge(int from, int to, int weight) { }
private final int n;
private final List<List<Edge>> adjacency = new ArrayList<>();
private final List<Edge> edges = new ArrayList<>();
private boolean hasNegativeEdge;
public Graph(int vertexCount) {
this.n = vertexCount;
for (int i = 0; i < n; i++) {
adjacency.add(new ArrayList<>());
}
}
public Graph addEdge(int from, int to, int weight) {
Edge e = new Edge(from, to, weight);
adjacency.get(from).add(e);
edges.add(e);
if (weight < 0) {
hasNegativeEdge = true;
}
return this;
}
public Graph addUndirected(int a, int b, int weight) {
addEdge(a, b, weight);
addEdge(b, a, weight);
return this;
}
public int size() {
return n;
}
public List<Edge> from(int u) {
return adjacency.get(u);
}
/** Every directed edge, in insertion order. An undirected edge appears twice. */
public List<Edge> edges() {
return edges;
}
public boolean hasNegativeEdge() {
return hasNegativeEdge;
}
}
@@ -0,0 +1,52 @@
package com.ankurm.interviewlab.graph;
import com.ankurm.interviewlab.graph.Graph.Edge;
import java.util.Arrays;
/** Small, deliberately wrong versions of the algorithms, so the article can show the symptom of each mistake. */
public final class Pitfalls {
private Pitfalls() { }
/** Bellman-Ford with an {@code int} infinity. The unreachable vertices are the problem. */
public static int[] bellmanFordIntInfinity(Graph g, int source) {
int[] dist = new int[g.size()];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[source] = 0;
for (int pass = 1; pass < g.size(); pass++) {
for (Edge e : g.edges()) {
if (dist[e.from()] + e.weight() < dist[e.to()]) { // no "is it reachable?" check
dist[e.to()] = dist[e.from()] + e.weight();
}
}
}
return dist;
}
/** A Union-Find whose union forgets to look up the roots first. */
public static final class BuggyUnionFind {
private final int[] parent;
public BuggyUnionFind(int n) {
parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public int find(int x) {
while (parent[x] != x) {
x = parent[x];
}
return x;
}
public void union(int a, int b) {
parent[a] = b; // BUG: a and b are not necessarily roots
}
public boolean connected(int a, int b) {
return find(a) == find(b);
}
}
}
@@ -0,0 +1,67 @@
package com.ankurm.interviewlab.graph;
import com.ankurm.interviewlab.graph.Graph.Edge;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
/** Minimum spanning trees on an undirected graph built with {@link Graph#addUndirected}. */
public final class SpanningTree {
/** {@code spanning == false} means the graph is disconnected and {@code edges} is a spanning forest. */
public record Result(long totalWeight, List<Edge> edges, boolean spanning) { }
private SpanningTree() { }
/** Kruskal: sort the edges, keep each one that joins two different components. Uses Union-Find. */
public static Result kruskal(Graph g) {
List<Edge> sorted = new ArrayList<>();
for (Edge e : g.edges()) {
if (e.from() < e.to()) { // each undirected edge is stored twice; keep one direction
sorted.add(e);
}
}
sorted.sort(Comparator.comparingInt(Edge::weight));
UnionFind uf = new UnionFind(g.size(), UnionFind.Strategy.BY_SIZE_AND_COMPRESSION);
List<Edge> chosen = new ArrayList<>();
long total = 0;
for (Edge e : sorted) {
if (uf.union(e.from(), e.to())) {
chosen.add(e);
total += e.weight();
}
}
return new Result(total, chosen, uf.components() == 1);
}
/** Prim: grow one tree from vertex 0, always taking the cheapest edge that leaves it. Uses a heap. */
public static Result prim(Graph g) {
int n = g.size();
boolean[] inTree = new boolean[n];
List<Edge> chosen = new ArrayList<>();
long total = 0;
int reached = 0;
for (int start = 0; start < n; start++) {
if (inTree[start]) {
continue;
}
PriorityQueue<Edge> pq = new PriorityQueue<>(Comparator.comparingInt(Edge::weight));
inTree[start] = true;
reached++;
pq.addAll(g.from(start));
while (!pq.isEmpty()) {
Edge e = pq.poll();
if (inTree[e.to()]) {
continue;
}
inTree[e.to()] = true;
reached++;
chosen.add(e);
total += e.weight();
pq.addAll(g.from(e.to()));
}
}
return new Result(total, chosen, chosen.size() == n - 1);
}
}
@@ -0,0 +1,161 @@
package com.ankurm.interviewlab.graph;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.PriorityQueue;
/**
* Topological ordering of a directed graph given as edges {@code {before, after}}.
* {@code acyclic == false} means the graph has a cycle and {@code order} is only the part that could be ordered.
*/
public final class TopologicalSort {
public record Order(List<Integer> order, boolean acyclic) { }
private TopologicalSort() { }
private static List<List<Integer>> adjacency(int n, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
}
return adj;
}
private static int[] indegrees(int n, int[][] edges) {
int[] indegree = new int[n];
for (int[] e : edges) {
indegree[e[1]]++;
}
return indegree;
}
/** Kahn's algorithm: repeatedly remove a vertex with no remaining prerequisites. */
public static Order kahn(int n, int[][] edges) {
List<List<Integer>> adj = adjacency(n, edges);
int[] indegree = indegrees(n, edges);
Deque<Integer> ready = new ArrayDeque<>();
for (int v = 0; v < n; v++) {
if (indegree[v] == 0) {
ready.add(v);
}
}
List<Integer> order = new ArrayList<>();
while (!ready.isEmpty()) {
int u = ready.poll();
order.add(u);
for (int v : adj.get(u)) {
if (--indegree[v] == 0) {
ready.add(v);
}
}
}
return new Order(order, order.size() == n);
}
/** Kahn's algorithm with a heap, so ties are broken by the smallest vertex number. */
public static Order kahnSmallestFirst(int n, int[][] edges) {
List<List<Integer>> adj = adjacency(n, edges);
int[] indegree = indegrees(n, edges);
PriorityQueue<Integer> ready = new PriorityQueue<>();
for (int v = 0; v < n; v++) {
if (indegree[v] == 0) {
ready.add(v);
}
}
List<Integer> order = new ArrayList<>();
while (!ready.isEmpty()) {
int u = ready.poll();
order.add(u);
for (int v : adj.get(u)) {
if (--indegree[v] == 0) {
ready.add(v);
}
}
}
return new Order(order, order.size() == n);
}
/** Kahn's algorithm one layer at a time: everything in a layer can run in parallel. */
public static List<List<Integer>> kahnLevels(int n, int[][] edges) {
List<List<Integer>> adj = adjacency(n, edges);
int[] indegree = indegrees(n, edges);
List<Integer> current = new ArrayList<>();
for (int v = 0; v < n; v++) {
if (indegree[v] == 0) {
current.add(v);
}
}
List<List<Integer>> levels = new ArrayList<>();
while (!current.isEmpty()) {
levels.add(current);
List<Integer> next = new ArrayList<>();
for (int u : current) {
for (int v : adj.get(u)) {
if (--indegree[v] == 0) {
next.add(v);
}
}
}
java.util.Collections.sort(next); // fixed order inside a layer, so output is reproducible
current = next;
}
return levels;
}
/** The recursive DFS version: reverse finishing order. Simple, but its recursion depth is the longest path. */
public static Order dfs(int n, int[][] edges) {
List<List<Integer>> adj = adjacency(n, edges);
int[] state = new int[n]; // 0 = new, 1 = on the current path, 2 = finished
List<Integer> finished = new ArrayList<>();
boolean[] cycle = {false};
for (int v = 0; v < n; v++) {
if (state[v] == 0) {
visit(v, adj, state, finished, cycle);
}
}
List<Integer> order = new ArrayList<>(finished);
java.util.Collections.reverse(order);
return new Order(order, !cycle[0]);
}
private static void visit(int u, List<List<Integer>> adj, int[] state, List<Integer> finished, boolean[] cycle) {
state[u] = 1;
for (int v : adj.get(u)) {
if (state[v] == 1) {
cycle[0] = true;
} else if (state[v] == 0) {
visit(v, adj, state, finished, cycle);
}
}
state[u] = 2;
finished.add(u);
}
/** True when every edge goes from an earlier position to a later one and each vertex appears exactly once. */
public static boolean isValidOrder(int n, int[][] edges, List<Integer> order) {
if (order.size() != n) {
return false;
}
int[] position = new int[n];
java.util.Arrays.fill(position, -1);
for (int i = 0; i < n; i++) {
int v = order.get(i);
if (v < 0 || v >= n || position[v] != -1) {
return false;
}
position[v] = i;
}
for (int[] e : edges) {
if (position[e[0]] >= position[e[1]]) {
return false;
}
}
return true;
}
}
@@ -0,0 +1,113 @@
package com.ankurm.interviewlab.graph;
/**
* Disjoint-set union (Union-Find). The {@link Strategy} switches the two classic optimisations on and off so a test
* can measure what each one buys.
*/
public final class UnionFind {
public enum Strategy {
NAIVE(false, false),
BY_SIZE(true, false),
COMPRESSION(false, true),
BY_SIZE_AND_COMPRESSION(true, true);
final boolean bySize;
final boolean compression;
Strategy(boolean bySize, boolean compression) {
this.bySize = bySize;
this.compression = compression;
}
}
private final int[] parent;
private final int[] size;
private final Strategy strategy;
private int components;
private long hops;
public UnionFind(int n, Strategy strategy) {
this.parent = new int[n];
this.size = new int[n];
this.strategy = strategy;
this.components = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
/** The representative of x's set. Counts every parent pointer followed in {@link #hops()}. */
public int find(int x) {
int root = x;
while (parent[root] != root) {
root = parent[root];
hops++;
}
if (strategy.compression) {
while (parent[x] != root) {
int next = parent[x];
parent[x] = root;
x = next;
}
}
return root;
}
/** Joins the sets of a and b. Returns false when they were already in the same set. */
public boolean union(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) {
return false;
}
if (strategy.bySize && size[ra] > size[rb]) {
int tmp = ra;
ra = rb;
rb = tmp;
}
parent[ra] = rb;
size[rb] += size[ra];
components--;
return true;
}
public boolean connected(int a, int b) {
return find(a) == find(b);
}
public int components() {
return components;
}
public long hops() {
return hops;
}
/** The longest chain of parent pointers from any vertex to its root. Does not change the structure. */
public int maxDepth() {
int n = parent.length;
int[] depth = new int[n];
java.util.Arrays.fill(depth, -1);
int max = 0;
int[] stack = new int[n];
for (int v = 0; v < n; v++) {
int top = 0;
int x = v;
while (depth[x] == -1 && parent[x] != x) {
stack[top++] = x;
x = parent[x];
}
if (depth[x] == -1) {
depth[x] = 0;
}
int d = depth[x];
while (top > 0) {
depth[stack[--top]] = ++d;
}
max = Math.max(max, depth[v]);
}
return max;
}
}
@@ -0,0 +1,140 @@
package com.ankurm.interviewlab.graph;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.graph.support.Transcript;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.junit.jupiter.api.Test;
class DijkstraTest {
private static final String NAMES = "ABCDEF";
/** The six-vertex graph used for the hand trace: A=0 ... F=5, undirected. */
static Graph classic() {
return new Graph(6)
.addUndirected(0, 1, 7).addUndirected(0, 2, 9).addUndirected(0, 5, 14)
.addUndirected(1, 2, 10).addUndirected(1, 3, 15).addUndirected(2, 3, 11)
.addUndirected(2, 5, 2).addUndirected(3, 4, 6).addUndirected(4, 5, 9);
}
static Graph randomGraph(Random rnd, int n, int m, int maxWeight) {
Graph g = new Graph(n);
for (int i = 0; i < m; i++) {
g.addEdge(rnd.nextInt(n), rnd.nextInt(n), 1 + rnd.nextInt(maxWeight));
}
return g;
}
@Test
void handTraceOnTheClassicGraph() {
Transcript t = Transcript.start("01-dijkstra-trace.txt", "Dijkstra trace, classic 6-vertex graph, source A");
List<String> trace = new ArrayList<>();
Dijkstra.Result r = Dijkstra.run(classic(), 0, true, trace::add);
trace.forEach(t::line);
t.blank();
for (int v = 0; v < 6; v++) {
t.line("dist[" + NAMES.charAt(v) + "] = " + r.dist()[v]);
}
List<Integer> pathToE = r.pathTo(4);
StringBuilder path = new StringBuilder();
for (int v : pathToE) {
path.append(path.isEmpty() ? "" : " -> ").append(NAMES.charAt(v));
}
t.blank().line("cheapest path to E: " + path + " (cost " + r.dist()[4] + ")");
t.blank().line("stats: " + r.stats());
t.flush();
assertArrayEquals(new long[] {0, 7, 9, 20, 20, 11}, r.dist());
assertEquals(List.of(0, 2, 5, 4), pathToE);
}
@Test
void staleEntriesCostWorkButNotCorrectness() {
Graph g = randomGraph(new Random(7), 2000, 10_000, 100);
Dijkstra.Result skip = Dijkstra.run(g, 0, true, null);
Dijkstra.Result noSkip = Dijkstra.run(g, 0, false, null);
Transcript t = Transcript.start("02-dijkstra-stale-entries.txt",
"Lazy deletion: with and without the stale-entry check (seeded graph, V=2000, E=10000)");
t.line("with check : " + skip.stats());
t.line("without check : " + noSkip.stats());
t.blank().line("same distances: " + java.util.Arrays.equals(skip.dist(), noSkip.dist()));
t.flush();
assertArrayEquals(skip.dist(), noSkip.dist());
assertTrue(skip.stats().stalePops() > 0);
assertTrue(skip.stats().edgeScans() < noSkip.stats().edgeScans());
assertEquals(skip.stats().pushes(), skip.stats().pops());
}
@Test
void agreesWithBellmanFordOnRandomGraphs() {
Random rnd = new Random(2026);
int cases = 3000;
int unreachableSeen = 0;
for (int c = 0; c < cases; c++) {
int n = 2 + rnd.nextInt(8);
Graph g = randomGraph(rnd, n, rnd.nextInt(n * 3), 20);
int src = rnd.nextInt(n);
long[] fast = Dijkstra.run(g, src).dist();
long[] slow = BellmanFord.run(g, src).dist();
assertArrayEquals(slow, fast, "case " + c);
for (long d : fast) {
if (d == Dijkstra.INF) {
unreachableSeen++;
break;
}
}
}
Transcript.start("03-dijkstra-vs-bellman-ford.txt", "Dijkstra vs Bellman-Ford on seeded random graphs")
.line("cases checked : " + cases)
.line("cases with an unreachable vertex: " + unreachableSeen)
.line("disagreements : 0")
.flush();
assertTrue(unreachableSeen > 0);
}
@Test
void negativeEdges() {
// A=0, B=1, C=2. A->B 1, A->C 2, C->B -5. The true distance to B is 2 + (-5) = -3.
Graph g = new Graph(3).addEdge(0, 1, 1).addEdge(0, 2, 2).addEdge(2, 1, -5);
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> Dijkstra.run(g, 0));
long[] visitedSet = Dijkstra.runWithVisitedSet(g, 0);
Dijkstra.Result lazy = Dijkstra.runWithoutNegativeCheck(g, 0);
BellmanFord.Result bf = BellmanFord.run(g, 0);
Transcript t = Transcript.start("04-negative-edges.txt", "One negative edge: A->B 1, A->C 2, C->B -5");
t.line("Dijkstra.run(g, A) throws : " + ex.getMessage());
t.line("visited-set version, dist[B] : " + visitedSet[1]);
t.line("lazy version, check removed, dist[B]: " + lazy.dist()[1] + " (pops " + lazy.stats().pops() + ")");
t.line("Bellman-Ford, dist[B] : " + bf.dist()[1]);
t.flush();
assertEquals(1, visitedSet[1]);
assertEquals(-3, bf.dist()[1]);
}
@Test
void quadraticVersusHeap() {
Random rnd = new Random(11);
Graph sparse = randomGraph(rnd, 2000, 8_000, 50);
Graph dense = randomGraph(rnd, 600, 150_000, 50);
Transcript t = Transcript.start("05-quadratic-vs-heap.txt", "Array scan O(V^2) vs binary heap: work counted, not timed");
for (Object[] row : new Object[][] {{"sparse V=2000 E=8000", sparse}, {"dense V=600 E=150000", dense}}) {
Graph g = (Graph) row[1];
Dijkstra.QuadraticResult q = Dijkstra.runQuadratic(g, 0);
Dijkstra.Result h = Dijkstra.run(g, 0);
assertArrayEquals(q.dist(), h.dist());
t.line(row[0] + ":");
t.line(" array version : min-scan steps " + q.minScanSteps());
t.line(" heap version : pushes " + h.stats().pushes() + ", pops " + h.stats().pops()
+ ", edge scans " + h.stats().edgeScans());
}
t.flush();
}
}
@@ -0,0 +1,47 @@
package com.ankurm.interviewlab.graph;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.graph.support.Transcript;
import org.junit.jupiter.api.Test;
class PitfallsTest {
@Test
void intInfinityOverflows() {
// 0 -> 1 weight 4; vertices 2 and 3 are unreachable, with an edge 2 -> 3 of weight 5.
Graph g = new Graph(4).addEdge(0, 1, 4).addEdge(2, 3, 5);
int[] wrong = Pitfalls.bellmanFordIntInfinity(g, 0);
long[] right = BellmanFord.run(g, 0).dist();
Transcript t = Transcript.start("12-pitfall-int-infinity.txt", "Bellman-Ford with int infinity: 2 -> 3 is unreachable from 0");
t.line("Integer.MAX_VALUE + 5 = " + (Integer.MAX_VALUE + 5));
t.line("int version, dist[3] : " + wrong[3]);
t.line("long + check, dist[3] : " + (right[3] == Dijkstra.INF ? "unreachable (INF)" : right[3]));
t.flush();
assertEquals(Integer.MAX_VALUE + 5, wrong[3]);
assertTrue(wrong[3] < 0);
assertEquals(Dijkstra.INF, right[3]);
}
@Test
void unionWithoutFindLosesAConnection() {
Pitfalls.BuggyUnionFind bad = new Pitfalls.BuggyUnionFind(3);
UnionFind good = new UnionFind(3, UnionFind.Strategy.BY_SIZE_AND_COMPRESSION);
bad.union(0, 1);
bad.union(0, 2);
good.union(0, 1);
good.union(0, 2);
Transcript t = Transcript.start("13-pitfall-union-without-find.txt", "union(0,1) then union(0,2), then ask connected(0,1)");
t.line("buggy connected(0,1): " + bad.connected(0, 1));
t.line("correct connected(0,1): " + good.connected(0, 1));
t.flush();
assertFalse(bad.connected(0, 1));
assertTrue(good.connected(0, 1));
}
}
@@ -0,0 +1,70 @@
package com.ankurm.interviewlab.graph;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.graph.Graph.Edge;
import com.ankurm.interviewlab.graph.SpanningTree.Result;
import com.ankurm.interviewlab.graph.support.Transcript;
import java.util.Random;
import org.junit.jupiter.api.Test;
class SpanningTreeTest {
private static final String NAMES = "ABCDEF";
@Test
void kruskalAndPrimAgree() {
Result k = SpanningTree.kruskal(DijkstraTest.classic());
Result p = SpanningTree.prim(DijkstraTest.classic());
Random rnd = new Random(2026);
int cases = 2000;
int disconnected = 0;
for (int c = 0; c < cases; c++) {
int n = 2 + rnd.nextInt(8);
Graph g = new Graph(n);
int m = rnd.nextInt(n * 2);
for (int i = 0; i < m; i++) {
int a = rnd.nextInt(n);
int b = rnd.nextInt(n);
if (a != b) {
g.addUndirected(a, b, 1 + rnd.nextInt(10));
}
}
Result kr = SpanningTree.kruskal(g);
Result pr = SpanningTree.prim(g);
assertEquals(kr.totalWeight(), pr.totalWeight(), "total weight, case " + c);
assertEquals(kr.edges().size(), pr.edges().size(), "edge count, case " + c);
assertEquals(kr.spanning(), pr.spanning(), "spanning flag, case " + c);
if (!kr.spanning()) {
disconnected++;
}
}
Transcript t = Transcript.start("11-kruskal-prim.txt", "Minimum spanning tree of the classic 6-vertex graph");
t.line("Kruskal total weight: " + k.totalWeight());
for (Edge e : k.edges()) {
t.line(" " + NAMES.charAt(e.from()) + " - " + NAMES.charAt(e.to()) + " (" + e.weight() + ")");
}
t.line("Prim total weight : " + p.totalWeight());
t.blank().line("random graphs checked : " + cases);
t.line("of which disconnected : " + disconnected);
t.line("Kruskal/Prim disagreements : 0");
t.flush();
assertEquals(33, k.totalWeight());
assertEquals(k.totalWeight(), p.totalWeight());
assertTrue(k.spanning());
assertTrue(disconnected > 0);
}
@Test
void disconnectedGraphGivesAForest() {
Graph g = new Graph(4).addUndirected(0, 1, 5).addUndirected(2, 3, 7);
Result r = SpanningTree.kruskal(g);
assertFalse(r.spanning());
assertEquals(12, r.totalWeight());
}
}
@@ -0,0 +1,137 @@
package com.ankurm.interviewlab.graph;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.graph.TopologicalSort.Order;
import com.ankurm.interviewlab.graph.support.Transcript;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.junit.jupiter.api.Test;
class TopologicalSortTest {
private static final String[] COURSES = {"Intro", "Maths", "DSA", "DBMS", "OS", "Networks", "Compilers"};
/** Prerequisite -> course. */
private static final int[][] PREREQS = {{0, 2}, {1, 2}, {0, 3}, {2, 4}, {3, 5}, {4, 5}, {2, 6}, {4, 6}};
private static String names(List<Integer> ids) {
List<String> out = new ArrayList<>();
for (int id : ids) {
out.add(COURSES[id]);
}
return String.join(", ", out);
}
@Test
void courseSchedule() {
Order kahn = TopologicalSort.kahn(7, PREREQS);
Order smallest = TopologicalSort.kahnSmallestFirst(7, PREREQS);
List<List<Integer>> levels = TopologicalSort.kahnLevels(7, PREREQS);
int[][] withCycle = {{0, 1}, {1, 2}, {2, 1}, {2, 3}};
Order cyclic = TopologicalSort.kahn(4, withCycle);
Transcript t = Transcript.start("06-kahn-course-schedule.txt", "Kahn's algorithm on a 7-course prerequisite graph");
t.line("kahn (queue order) : " + names(kahn.order()) + " acyclic=" + kahn.acyclic());
t.line("kahn (smallest first): " + names(smallest.order()) + " acyclic=" + smallest.acyclic());
for (int i = 0; i < levels.size(); i++) {
t.line("semester " + (i + 1) + " : " + names(levels.get(i)));
}
t.blank().line("cycle 1->2->1 plus 2->3, kahn returns: " + cyclic.order() + " acyclic=" + cyclic.acyclic());
t.line("(vertex 0 is the only one that could be ordered; the flag is the only signal of the cycle)");
t.flush();
assertTrue(TopologicalSort.isValidOrder(7, PREREQS, kahn.order()));
assertTrue(TopologicalSort.isValidOrder(7, PREREQS, smallest.order()));
assertEquals(List.of(List.of(0, 1), List.of(2, 3), List.of(4), List.of(5, 6)), levels);
assertFalse(cyclic.acyclic());
assertEquals(List.of(0), cyclic.order());
}
/** Reference cycle check: a graph has a cycle iff some vertex can reach itself. */
private static boolean hasCycle(int n, int[][] edges) {
boolean[][] reach = new boolean[n][n];
for (int[] e : edges) {
reach[e[0]][e[1]] = true;
}
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (reach[i][k] && reach[k][j]) {
reach[i][j] = true;
}
}
}
}
for (int i = 0; i < n; i++) {
if (reach[i][i]) {
return true;
}
}
return false;
}
@Test
void randomGraphsAgreeWithReferenceCheck() {
Random rnd = new Random(2026);
int cases = 3000;
int cyclic = 0;
for (int c = 0; c < cases; c++) {
int n = 1 + rnd.nextInt(8);
int m = rnd.nextInt(n * 2 + 1);
int[][] edges = new int[m][];
for (int i = 0; i < m; i++) {
edges[i] = new int[] {rnd.nextInt(n), rnd.nextInt(n)};
}
boolean expectCycle = hasCycle(n, edges);
Order k = TopologicalSort.kahn(n, edges);
Order d = TopologicalSort.dfs(n, edges);
assertEquals(!expectCycle, k.acyclic(), "kahn flag, case " + c);
assertEquals(!expectCycle, d.acyclic(), "dfs flag, case " + c);
if (expectCycle) {
cyclic++;
} else {
assertTrue(TopologicalSort.isValidOrder(n, edges, k.order()), "kahn order, case " + c);
assertTrue(TopologicalSort.isValidOrder(n, edges, d.order()), "dfs order, case " + c);
}
}
Transcript.start("07-topological-random-agreement.txt", "Kahn and DFS vs a transitive-closure reference on seeded random graphs")
.line("cases checked : " + cases)
.line("cases with a cycle : " + cyclic)
.line("cases acyclic (orders valid): " + (cases - cyclic))
.line("disagreements : 0")
.flush();
assertTrue(cyclic > 0 && cyclic < cases);
}
@Test
void recursionDepthIsTheLongestPath() throws Exception {
int n = 100_000;
int[][] chain = new int[n - 1][];
for (int i = 0; i < n - 1; i++) {
chain[i] = new int[] {i, i + 1};
}
String[] dfsResult = new String[1];
Thread worker = new Thread(null, () -> {
try {
dfsResult[0] = "completed, acyclic=" + TopologicalSort.dfs(n, chain).acyclic();
} catch (StackOverflowError e) {
dfsResult[0] = "StackOverflowError";
}
}, "dfs-small-stack", 512 * 1024);
worker.start();
worker.join();
Order kahn = TopologicalSort.kahn(n, chain);
Transcript t = Transcript.start("08-recursion-depth.txt", "A 100,000-vertex chain on a thread with a 512 KB stack");
t.line("recursive DFS : " + dfsResult[0]);
t.line("Kahn : ordered " + kahn.order().size() + " vertices, acyclic=" + kahn.acyclic());
t.flush();
assertEquals("StackOverflowError", dfsResult[0]);
assertTrue(kahn.acyclic());
}
}
@@ -0,0 +1,133 @@
package com.ankurm.interviewlab.graph;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.ankurm.interviewlab.graph.UnionFind.Strategy;
import com.ankurm.interviewlab.graph.support.Transcript;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.junit.jupiter.api.Test;
class UnionFindTest {
@Test
void chainOfUnionsShowsWhatEachOptimisationBuys() {
int n = 20_000;
Transcript t = Transcript.start("09-union-find-chain.txt",
"union(0,1), union(1,2), ... union(n-2,n-1) with n=" + n + ", then find(0) twice");
int naiveDepth = -1;
int bySizeDepth = -1;
for (Strategy s : Strategy.values()) {
UnionFind uf = new UnionFind(n, s);
for (int i = 0; i < n - 1; i++) {
uf.union(i, i + 1);
}
int depth = uf.maxDepth();
long before = uf.hops();
uf.find(0);
long firstFind = uf.hops() - before;
before = uf.hops();
uf.find(0);
long secondFind = uf.hops() - before;
t.line(String.format("%-24s max depth %6d | find(0) #1: %6d hops | find(0) #2: %6d hops",
s, depth, firstFind, secondFind));
assertEquals(1, uf.components());
if (s == Strategy.NAIVE) {
naiveDepth = depth;
}
if (s == Strategy.BY_SIZE) {
bySizeDepth = depth;
}
}
int pairs = 1 << 14; // 16384 vertices, merged in rounds of equal-sized sets
t.blank().line("Tournament pattern, n=" + pairs + ": round r joins sets of size 2^r, so equal sizes meet every time");
int tournamentBySize = -1;
for (Strategy s : Strategy.values()) {
UnionFind uf = new UnionFind(pairs, s);
for (int step = 1; step < pairs; step *= 2) {
for (int i = 0; i < pairs; i += 2 * step) {
uf.union(i, i + step);
}
}
t.line(String.format("%-24s max depth %6d", s, uf.maxDepth()));
if (s == Strategy.BY_SIZE) {
tournamentBySize = uf.maxDepth();
}
}
t.flush();
assertEquals(n - 1, naiveDepth);
assertEquals(1, bySizeDepth);
assertEquals(14, tournamentBySize, "log2(16384) = 14 is the worst case union by size can reach");
}
private static int bfsComponents(int n, List<int[]> edges) {
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
adj.get(e[1]).add(e[0]);
}
boolean[] seen = new boolean[n];
int count = 0;
for (int s = 0; s < n; s++) {
if (seen[s]) {
continue;
}
count++;
ArrayDeque<Integer> q = new ArrayDeque<>();
q.add(s);
seen[s] = true;
while (!q.isEmpty()) {
int u = q.poll();
for (int v : adj.get(u)) {
if (!seen[v]) {
seen[v] = true;
q.add(v);
}
}
}
}
return count;
}
@Test
void everyStrategyAgreesWithBfs() {
Random rnd = new Random(2026);
int cases = 2000;
for (int c = 0; c < cases; c++) {
int n = 1 + rnd.nextInt(15);
int m = rnd.nextInt(n + 3);
List<int[]> edges = new ArrayList<>();
for (int i = 0; i < m; i++) {
edges.add(new int[] {rnd.nextInt(n), rnd.nextInt(n)});
}
int expected = bfsComponents(n, edges);
for (Strategy s : Strategy.values()) {
UnionFind uf = new UnionFind(n, s);
for (int[] e : edges) {
uf.union(e[0], e[1]);
}
assertEquals(expected, uf.components(), s + " case " + c);
}
}
Transcript.start("10-union-find-random-agreement.txt", "Union-Find (all four strategies) vs BFS component count")
.line("cases checked : " + cases)
.line("strategies : " + java.util.Arrays.toString(Strategy.values()))
.line("disagreements : 0")
.flush();
}
@Test
void cycleDetectionInAnUndirectedGraph() {
UnionFind uf = new UnionFind(4, Strategy.BY_SIZE_AND_COMPRESSION);
assertTrue(uf.union(0, 1));
assertTrue(uf.union(1, 2));
assertFalse(uf.union(0, 2), "0 and 2 are already connected, so this edge closes a cycle");
}
}
@@ -0,0 +1,43 @@
package com.ankurm.interviewlab.graph.support;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Writes output/NN-*.txt while the calling test asserts the same numbers it prints. */
public final class Transcript {
private final Path path;
private final List<String> lines = new ArrayList<>();
private Transcript(Path path, String header) {
this.path = path;
lines.add(header);
lines.add("=".repeat(Math.min(header.length(), 100)));
lines.add("");
}
public static Transcript start(String fileName, String header) {
Path dir = Path.of("output");
try {
Files.createDirectories(dir);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return new Transcript(dir.resolve(fileName), header);
}
public Transcript line(String text) { lines.add(text); return this; }
public Transcript blank() { lines.add(""); return this; }
public void flush() {
try {
Files.write(path, (String.join("\n", lines) + "\n").getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}