Lesson 142 of 296
Topological sort and union-find
What you will learn
- Topological sort for dependencies
- Kahn's algorithm (BFS with in-degrees)
- Course Schedule I and II
- Detecting cycles in directed graphs
- Union-find (disjoint set union)
- Counting connected components
On this page
Topological sort
A topological order of a directed graph lists the nodes so that every edge goes forward: if A → B, A comes before B. Real uses: build order of software packages, course prerequisites, task scheduling, spreadsheet formula recalculation.
A topological order exists only if the graph has no cycles. (If A needs B and B needs A, neither can go first.) A directed graph with no cycles is called a DAG (Directed Acyclic Graph).
Kahn's algorithm
- Count each node's in-degree: how many edges point into it (how many prerequisites it has).
- Put every node with in-degree 0 (no prerequisites) in a queue.
- Repeatedly take a node from the queue, add it to the order, and remove its outgoing edges: reduce each neighbour's in-degree; when a neighbour reaches 0, queue it.
- If the order contains every node, it is valid. If not, the remaining nodes are part of a cycle.
Course Schedule
Problem (LeetCode 207): numCourses courses and prerequisites pairs [course, prerequisite]. Can you finish every course?
function findCourseOrder(numCourses: number, prerequisites: [number, number][]): number[] {
const graph: number[][] = Array.from({ length: numCourses }, () => []);
const inDegree = new Array<number>(numCourses).fill(0);
for (const [course, prereq] of prerequisites) {
graph[prereq]!.push(course);
inDegree[course]!++;
}
const order: number[] = [];
for (let c = 0; c < numCourses; c++) {
if (inDegree[c] === 0) order.push(c);
}
for (let head = 0; head < order.length; head++) {
const course = order[head]!;
for (const next of graph[course]!) {
inDegree[next]!--;
if (inDegree[next] === 0) order.push(next);
}
}
return order.length === numCourses ? order : [];
}
function canFinish(numCourses: number, prerequisites: [number, number][]): boolean {
return findCourseOrder(numCourses, prerequisites).length === numCourses;
}- The edge goes from the prerequisite to the course: you take the prerequisite first.
- The
orderarray also works as the queue (with aheadindex, Lesson 129). findCourseOrderis Course Schedule II (LeetCode 210): return a valid order, or an empty array if impossible.
O(V + E) time and space.
(A DFS-based topological sort also exists: it detects cycles with three states per node: unvisited, visiting, done. Meeting a "visiting" node again means a cycle.)
Union-find
Union-find (also called disjoint set union, DSU) keeps track of items split into groups. It supports two operations, both almost O(1):
- find(x): which group is x in? (Returns the group's representative, its root.)
- union(a, b): merge the groups of a and b.
It answers "are these two connected?" very quickly while edges are being added. Uses: counting connected components, detecting cycles in undirected graphs, Kruskal's algorithm for minimum spanning trees, grouping accounts that share an email.
Each item points to a parent; a root points to itself.
Two optimisations make it almost O(1) per operation:
- Path compression: during
find, point every node on the way directly to the root. - Union by rank (or size): attach the smaller tree under the larger one, so trees stay flat.
class UnionFind {
private parent: number[];
private rank: number[];
count: number;
constructor(n: number) {
this.parent = Array.from({ length: n }, (_, i) => i);
this.rank = new Array<number>(n).fill(0);
this.count = n;
}
find(x: number): number {
if (this.parent[x] !== x) {
this.parent[x] = this.find(this.parent[x]!);
}
return this.parent[x]!;
}
union(a: number, b: number): boolean {
const rootA = this.find(a);
const rootB = this.find(b);
if (rootA === rootB) return false;
if (this.rank[rootA]! < this.rank[rootB]!) {
this.parent[rootA] = rootB;
} else if (this.rank[rootA]! > this.rank[rootB]!) {
this.parent[rootB] = rootA;
} else {
this.parent[rootB] = rootA;
this.rank[rootA]!++;
}
this.count--;
return true;
}
}union returns false if the two were already connected. In an undirected graph, adding an edge between two already-connected nodes creates a cycle: that is the "Redundant Connection" problem (LeetCode 684).
Number of Connected Components
Problem (LeetCode 323): n nodes and undirected edges; how many separate groups?
function countComponents(n: number, edges: [number, number][]): number {
const uf = new UnionFind(n);
for (const [a, b] of edges) uf.union(a, b);
return uf.count;
}Start with n groups; each successful union merges two into one. (DFS or BFS from each unvisited node also works, O(V + E).)
How to say it in an interview
"A topological sort orders a DAG so every edge points forward, which models dependencies like course prerequisites. With Kahn's algorithm I compute in-degrees, queue every node with in-degree zero, and remove edges as I process nodes; if not every node is output, there is a cycle. Union-find tracks groups with find and union; with path compression and union by rank both are nearly constant time. I use it for connected components and for detecting cycles in undirected graphs, since uniting two nodes already in the same set means a cycle."
Key words
| Word | Meaning |
|---|---|
| Topological sort | Ordering nodes so all edges point forward |
| DAG | Directed acyclic graph: directed with no cycles |
| In-degree | The number of edges pointing into a node |
| Kahn's algorithm | BFS-based topological sort using in-degrees |
| Union-find | A structure for merging groups and finding which group an item is in |
| Path compression | Pointing nodes directly to their root during find |
| Union by rank | Attaching the shorter tree under the taller one |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.