Data Structures & Algorithms (DSA) Interview Mastery · Chapter 10 · ~15 min · Advanced
Graphs 2: Topological Sort & Union-Find
Master Directed Acyclic Graphs (DAGs) and dynamic connectivity: learn Kahn's algorithm with in-degree tracking for Course Schedules, detect cycles in dependency trees, and build Union-Find with Path Compression and Union by Rank.
- Understand Directed Acyclic Graphs (DAG) and dependency ordering
- Implement Kahn's Algorithm for Topological Sort using in-degree queues
- Detect cycles in directed graphs to identify impossible dependency loops
- Build Disjoint Set Union (DSU) with Path Compression and Union by Rank
Graphs 2: Topological Sort & Union-Find: learn it visually
Master Directed Acyclic Graphs (DAGs) and dynamic connectivity: learn Kahn's algorithm with in-degree tracking for Course Schedules, detect cycles in dependency trees, and build Union-Find with Path Compression and Union by Rank.
1Everyday Intuition: Course Prerequisites & Friend Merges
Think about registering for college courses: before you take Data Structures (CS201), you must take Intro to Programming (CS101) and Discrete Math (MATH100). You cannot take them in any random order; there is an inherent linear dependency constraint.
This is exactly how compilers build source code (Webpack, Make, Rust Cargo), how CI/CD pipelines schedule task stages, and how database migrations execute without foreign key violations.
Topological Sort (DAGs)
Given directed edges u → v, order all vertices linearly such that for every edge, u appears strictly before v. Only possible if the graph has no directed cycles (a DAG).
Union-Find (Disjoint Set Union)
Tracks partitioned sets of elements across dynamic connections. Supports two operations in near O(1) time: find(p) (which group does p belong to?) and union(p, q) (merge group p and group q). The backbone of Kruskal's Minimum Spanning Tree algorithm.
What is the necessary condition for a directed graph to have at least one valid topological ordering?
2Architecture & Code Mechanics: Kahn's Algorithm & DSU
Let's explore the two canonical patterns interviewers test: Kahn's in-degree queue algorithm and the DisjointSet class with path compression.
Wrong idea: Greedy DFS without in-degree prerequisite checking
Simply traversing outgoing edges from an arbitrary start node risks processing dependent tasks before their mandatory prerequisites have completed, or hanging in infinite recursion if cycles exist.
Real system: Kahn's Algorithm: In-Degree Array + Zero-In-Degree Queue
Count prerequisite requirements for every node (`in_degree[u]`). Only enqueue nodes with in-degree 0 (no prerequisites). When a node finishes, decrement its dependents' in-degrees by 1.
Canonical Python Implementation: Production Union-Find (DSU)
class UnionFind:
def __init__(self, n):
# Every element is initially its own parent root
self.parent = list(range(n))
self.rank = [0] * n
self.components = n
def find(self, x):
# Path Compression: flattens the tree directly to the root
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX == rootY:
return False # Already in same set (cycle detected!)
# Union by Rank: attach shorter tree under taller tree
if self.rank[rootX] < self.rank[rootY]:
self.parent[rootX] = rootY
elif self.rank[rootX] > self.rank[rootY]:
self.parent[rootY] = rootX
else:
self.parent[rootY] = rootX
self.rank[rootX] += 1
self.components -= 1
return TrueIn Kahn's Algorithm, how is a cycle in a directed graph detected?
3Interactive Visual Simulation: Course Schedule DAG
Experience Kahn's algorithm dynamically below. Nodes with in:0 have all prerequisites satisfied and can be clicked to graduate. Or click Inject Deadlock Cycle to witness a circular dependency deadlock:
Live Dependency DAG: Course Schedule Topological Sort
What is the amortized time complexity of Union-Find operations when both Path Compression and Union by Rank are enabled?
4Hands-On Challenge: Bug Hunt in Course Schedule
A backend service responsible for scheduling university course curricula has three critical defects: inverted dependency edges, a missing in-degree decrement, and missing cycle validation. Repair the algorithm below to achieve green passing checks:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- In
for course, prereq in prerequisites:, edge flows fromprereq → course. Writeadj[prereq].append(course)andin_degree[course] += 1. - Inside the while queue loop, decrement the neighbor's requirement:
in_degree[neighbor] -= 1. - Return
completed == num_coursesat the end to confirm zero cycle entrapment.
5Architecture Recap & Key Takeaways
- DAGs (Directed Acyclic Graphs): Necessary and sufficient condition for valid topological ordering.
- Kahn's Algorithm: Uses an in-degree counter and FIFO queue. Runs in linear
O(V + E)time. - Cycle Detection: If Kahn's queue empties before all
Vnodes are processed, a circular dependency deadlock exists. - Disjoint Set Union (DSU): Path Compression flattens parent pointers to the root; Union by Rank bounds tree height.
- Amortized O(α(N)): With both optimizations, DSU lookups and merges execute in near-instantaneous constant time.
Ready for Chapter 11 (Backtracking: Permutations, Subsets & N-Queens)? Mark as complete: