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.
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.
Cycles in directed graphs require directional tracking:
Kahn's algorithm uses vertex In-Degrees (number of incoming arrows) with a FIFO queue:
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].
| 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 |
A1 = B1 + C1) require topological evaluation. Circular references (A1 = B1 + 1 and B1 = A1 + 1) are flagged as illegal cycles.Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.