Browse curriculum

Depth-First Search

The Depth-First Search Pattern

Follow one path as far as it goes, then back up and try the next. On trees this gives the preorder, inorder and postorder traversals; on graphs it needs a visited set to avoid revisiting nodes.

25

Interactive problems

3

Free to open

Recognise

How do you recognise a depth-first search problem?

You need to explore every node, test whether a path exists, work with tree structure, or compute something that depends on a node’s children before the node itself — the postorder shape behind most tree DP.

Complexity

What is the time complexity of the depth-first search pattern?

O(V + E) time. Space is O(h) for the recursion stack, where h is depth — which is O(n) in the worst case for a skewed tree.

Problems

Depth-First Search practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Depth-First Search problems by difficulty and complexity

The difficulty, running time and extra space of every depth-first search solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Introduction to DFSEasyΩ(n)Θ(n)O(n)O(h)
DFS FundamentalsEasyΩ(n)Θ(n)O(n)O(h)
Return Values in DFSEasyΩ(n)Θ(n)O(n)O(h)
Invert Binary TreeEasyΩ(n)Θ(n)O(n)O(h)
Maximum Depth of Binary TreeEasyΩ(n)Θ(n)O(n)O(h)
Path SumEasyΩ(h)Θ(n)O(n)O(h)
Passing Values Down (State)MediumΩ(n)Θ(n)O(n)O(h)
Validate Binary Search TreeMediumΩ(1)Θ(n)O(n)O(h)
Kth Smallest Element in a BSTMediumΩ(h + k)Θ(h + k)O(n)O(h)
Construct Binary Tree from Preorder and Inorder TraversalMediumΩ(n)Θ(n)O(n)O(n)
Binary Tree TiltEasyΩ(n)Θ(n)O(n)O(h)
Diameter of Binary TreeEasyΩ(n)Θ(n)O(n)O(h)
Lowest Common Ancestor of a Binary TreeMediumΩ(1)Θ(n)O(n)O(h)
Path Sum IIMediumΩ(n)Θ(n log n)O(n²)O(n)
Longest Univalue PathMediumΩ(n)Θ(n)O(n)O(h)
Graphs OverviewMediumΩ(V + E)Θ(V + E)O(V + E)O(V + E)
Graph Representation: Adjacency ListMediumΩ(V + E)Θ(V + E)O(V + E)O(V + E)
Clone GraphMediumΩ(V + E)Θ(V + E)O(V + E)O(V)
Graph Valid TreeMediumΩ(V + E)Θ(V + E)O(V + E)O(V + E)
Matrices as GraphsMediumΩ(1)Θ(m·n)O(m·n)O(m·n)
Flood FillEasyΩ(1)Θ(m·n)O(m·n)O(m·n)
Types of DFS (Tree Traversals)MediumΩ(n)Θ(n)O(n)O(h)
Number of IslandsMediumΩ(m·n)Θ(m·n)O(m·n)O(m·n)
Surrounded RegionsMediumΩ(m·n)Θ(m·n)O(m·n)O(m·n)
Pacific Atlantic Water FlowMediumΩ(m·n)Θ(m·n)O(m·n)O(m·n)
Curriculum

The underlying technique is covered from first principles in the depth-first search lesson in the DSA visualizer curriculum. Depth-First Search is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern