Cycle Detection & Topological Sorting (Kahn's BFS & DFS)
Cycle Detection & Topological Sorting (Kahn's BFS & DFS)
In graph theory, detecting cycles and ordering dependencies are two fundamental problems encountered across build systems (Make/Gradle/Webpack), package managers (npm, pip), university course prerequisites, and relational database foreign key constraints.
1. What is Topological Sorting?
A Topological Sort of a Directed Acyclic Graph (DAG) is a linear ordering of its vertices such that for every directed edge $(u \to v)$, vertex $u$ comes before vertex $v$ in the sequence.
2. Cycle Detection Strategies
In Undirected Graphs
- 1DFS with Parent Tracking: During traversal, if a neighbor has already been visited and is NOT the immediate parent of the current node, an alternative path exists, proving a cycle!
- 2Disjoint Set Union (Union-Find): For each edge $(u, v)$, if $\text{Find}(u) == \text{Find}(v)$, both nodes already belong to the same connected component; adding edge $(u, v)$ creates a cycle.
In Directed Graphs
Cycles in directed graphs require directional tracking:
- 13-Color DFS:
- White (0): Unvisited node.
- Gray (1): Currently in the active recursion call stack (being explored).
- Black (2): Fully processed and all descendants explored.
- Cycle Condition: If DFS encounters an edge pointing to a Gray node, a Back Edge is found, confirming a directed cycle!
- 1Kahn's Algorithm (BFS In-Degree): If the final topological sort output contains fewer than $V$ vertices, an unresolved cycle prevented some nodes from ever reaching an in-degree of 0.
3. Kahn's Algorithm Step-by-Step
Kahn's algorithm uses vertex In-Degrees (number of incoming arrows) with a FIFO queue:
Trace Table for Kahn's Algorithm
Given $V = 4$, Edges: $0 \to 1, 0 \to 2, 1 \to 3, 2 \to 3$:
| Step | Queue (In-Degree 0) | Processed Node | Edge Removed | Updated In-Degrees [0, 1, 2, 3] | Result Array |
|---|---|---|---|---|---|
| Init | [0] | - | - | [0, 1, 1, 2] | [] |
| 1 | [] | 0 | $0 \to 1, 0 \to 2$ | [0, 0, 0, 2] (1 and 2 hit 0!) | [0] |
| 2 | [1, 2] | 1 | $1 \to 3$ | [0, 0, 0, 1] | [0, 1] |
| 3 | [2] | 2 | $2 \to 3$ | [0, 0, 0, 0] (3 hits 0!) | [0, 1, 2] |
| 4 | [3] | 3 | None | [0, 0, 0, 0] | [0, 1, 2, 3] |
All 4 nodes processed $\implies$ Valid DAG order: [0, 1, 2, 3].
4. Dual-Language Implementation
Python 3: Kahn's Algorithm & DFS 3-Coloring
Modern JavaScript (Node.js) Implementation
5. Complexity Analysis
| Algorithm | Time Complexity | Space Complexity | Best Feature |
|---|---|---|---|
| Kahn's Algorithm (BFS) | $O(V + E)$ | $O(V)$ | Simultaneously outputs valid ordering AND detects cycles |
| DFS 3-Coloring | $O(V + E)$ | $O(V)$ | Intuitive recursive cycle verification via back-edges |
| Undirected Union-Find | $O(E \cdot \alpha(V))$ | $O(V)$ | Ultra-fast dynamic cycle detection in undirected graphs |
6. Real-World Applications & Edge Cases
- 1Course Schedule (LeetCode 207 / 210): Direct mapping to Kahn's algorithm or 3-color DFS.
- 2Build Systems (Webpack, Make, Vite): Compilers parse import statements into a DAG. Circular imports (e.g., Module A imports Module B which imports Module A) trigger build cycle errors.
- 3Spreadsheet Formula Calculation: Cells with dependent formulas (e.g.,
A1 = B1 + C1) require topological evaluation. Circular references (A1 = B1 + 1andB1 = A1 + 1) are flagged as illegal cycles.
Multiple Choice Questions
Shortest Paths: Dijkstra's Algorithm with Min-Heap & BFS for Unweighted
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.