Lesson 60 of 86IntermediatePro Interactive Lesson

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

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

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.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.