Depth-First Search (DFS)
Follow the current branch until it cannot advance, then watch where the search backtracks.
Core Intuition & How It Works
Depth-First Search (DFS) follows one path as deep as possible before backtracking, using either recursion or an explicit stack. Its discovery and finish order powers cycle detection, topological sort, and component analysis.
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
Track visited vertices before recursing on neighbors, and switch to an explicit stack when graph depth could exceed recursion limits.
Common Pitfalls & Edge Cases
Using DFS to find shortest paths in an unweighted graph (DFS finds *a* path, not necessarily the shortest one).
Real-World & Technical Interview Applications
Maze solving, connected components, topological ordering, bridge/articulation finding, and garbage collection.