Pattern · Interview prep
Depth-First Search
Follow one branch until it ends, then return and take the next. The open path is a stack: the node you entered last is the one you finish next.
What it is
What is the depth-first search pattern?
Depth-first search goes down before it goes across. On a tree, the call stack is the path from the root to the current node. On a graph or a grid, you keep that path yourself and you mark what you have already seen, or the walk loops.
- A tree. An empty child stops the branch. Then you use the node and walk the other child. Left, then the node, then right is one common order.
- A graph or a grid. Push a neighbor the first time you discover it, and remember that it is seen. An explicit stack finishes one branch. A queue would finish the layer instead.
- A path you must undo. When you are trying candidates, add the node, explore, then remove it before the next choice. The same array is the path for every branch.
The left child is recorded before the root
When to use it
How do you recognize a depth-first search problem?
Read the statement for these signals before you reach for the shortest path.
Read the full recognition guide: DFS vs BFS: how to tell which one a problem needs
Phrases to watch for
- left and right child
- subtree
- connected component
- mark seen
- all paths
- cycle on the current path
- undo the choice
- 1
The answer is built from the children
Swap a subtree, list its values, or combine a sum from each side. Finish a child before you use this node.
- 2
You need membership, not distance
An island, a copied graph, or a component only asks which nodes belong together. The order inside the piece does not change the set.
- 3
A repeat on the open path is a cycle
A node you have finished is safe. A node still on the path you are walking means the rules loop.
Looks similar, but isn’t
You want the fewest steps
On an unweighted graph, the first time a queue reaches the target is the shortest path. Depth-first finds a path, then has to compare the others.
You want one level at a time
A queue holds the nodes discovered now and finishes them before their children. A stack would finish a deep branch first and reverse the level.
The row is sorted and you can discard half
Binary search jumps to the middle. Depth-first still walks a subtree when the question is about structure, not a lookup.
Worked example
How does one branch finish before the next?
Visit the left subtree, then record the node, then the right subtree. On a tree whose root is 2, with 1 on the left and 3 on the right, the values come out [1, 2, 3]. The same order shows up in the tree problems below.
type Node = { value: number; left: Node | null; right: Node | null }; function collectDepthFirst(root: Node | null): number[] { const values: number[] = []; const visit = (node: Node | null) => { if (node === null) return; visit(node.left); values.push(node.value); visit(node.right); }; visit(root); return values;}Finish the left child, record this node, then the right child.
Code is shown in TypeScript. You can solve problems in TypeScript, JavaScript, or Python.
Complexity
- TimeO(n)
Each node is entered once and recorded once.
- SpaceO(h)
The call stack holds the path from the root to the current node. A straight line of n nodes uses O(n).
An empty child
A null node returns at once. That is what lets a missing child end the branch instead of throwing.
The same walk on a grid
Replace the two children with the four edge neighbors. Mark a cell seen when you first discover it, not when you pop it, so it is not pushed twice.
Step by step on root 2, left 1, right 3
- 1
Enter 2 and go left. 1 has no left child, so the walk records 1 before it records anything above it.
1L·R23 - 2
1 has no right child either. The walk returns to 2 and records 2. The list so far is 1, then 2.
12L·R3 - 3
The right child is 3. Its left child is empty, so 3 is recorded next.
123L·R - 4
3 has no right child. The branch is finished. The values are
[1, 2, 3].123
Common mistakes
What mistakes do people make with depth-first search?
Using depth-first for the shortest unweighted path
The first path you finish can be a long detour. The fewest steps is the first time a level-by-level walk reaches the target.
InsteadUse a queue when every edge costs the same and the question asks for distance. Keep depth-first when you only need a component, a structure, or every path.
Marking a cell seen when you pop it
Two neighbors can both push the same unseen cell. You then walk it twice, and a count of islands goes up wrong or a copy grows duplicate edges.
InsteadMark the cell seen at the moment you discover it, before it goes on the stack.
Sharing a path and forgetting to undo
The next branch starts with the previous branch still in the array. Later answers include nodes that are not on their path.
InsteadPush, explore, then pop before the next choice. Copy the path only when you record an answer.
Checking a node only against its parent
A value can be greater than its parent and still be smaller than an ancestor that owns the whole subtree. The local check accepts a tree that is not ordered.
InsteadCarry the allowed range from the ancestors, or walk the values in order and reject a step that decreases.
Practice it in Algofily
Which Algofily problems train depth-first search?
8 problems are tagged Depth-First Search. Two easy tree walks are in Algofily 40. The rest check an ordered tree, a shared ancestor, a branching path, islands, a graph copy, and whether courses can finish.
- Locked: opens after you create an account. Mirror the TreeeasyDepth-First SearchSwap every left and right child in a binary tree, all the way down.Algofily 40Open problem
- Locked: opens after you create an account. Inorder WalkeasyDepth-First SearchReturn the values of a binary tree in inorder: every value in the left subtree, then the node’s own value, then every value in the right subtree.Algofily 40Open problem
- Locked: opens after you create an account. Ordered Tree CheckmediumBinary Search Tree · Depth-First SearchDecide whether a binary tree is a binary search tree.Open problem
- Locked: opens after you create an account. Shared AncestormediumDepth-First SearchValues in the binary tree are unique.Open problem
- Locked: opens after you create an account. Best Branching PathhardDepth-First Search · Dynamic ProgrammingA binary tree stores a number on every node.Open problem
- Locked: opens after you create an account. Island CountmediumDepth-First Search · Breadth-First SearchA grid of 0s and 1s is a map.Open problem
- Locked: opens after you create an account. Copy the GraphmediumDepth-First SearchAn undirected graph is an adjacency list.Open problem
- Locked: opens after you create an account. Courses Can FinishmediumBreadth-First Search · Depth-First SearchThere are courseCount courses, numbered from 0.Open problem
A lock means the problem opens after you create an account. Pair With Target is open to try without one.
Start Learning.
Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.