Lesson 62 of 86IntermediatePro Interactive Lesson

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

MetricComplexity
Time ComplexityO(V + E)
Space ComplexityO(V)
Topic ChapterChapter 11: Graph Traversal & Connectivity
Difficulty LevelIntermediate

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.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.