Detecting Cycles in a Directed Graph
Distinguish a vertex on the active DFS path from a vertex whose exploration has finished.
Core Intuition & How It Works
Detecting cycles in a directed graph uses three-color DFS (unvisited, visiting/in-stack, visited/done). A back-edge to a vertex currently in the active recursion stack proves a directed cycle exists.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(V + E) |
| Space Complexity | O(V) |
| Topic Chapter | Chapter 11: Graph Traversal & Connectivity |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Distinguish active recursion-stack nodes from already-finished nodes—a cross-edge to a finished node is NOT a cycle.
Common Pitfalls & Edge Cases
Using only a boolean visited set on a directed graph, which falsely flags diamond DAGs (A->B, A->C, B->D, C->D) as cycles.
Real-World & Technical Interview Applications
Deadlock detection, circular dependency checks in package managers, and spreadsheet formula validation.