Skip to content

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.
Root 2, left child 1, right child 3
order1, 2, 3

The left child is recorded before the root

LFirst recordedRLast recorded
A tree with visit numbers 1 to 7. Depth-first preorder goes down the left side first: 1 root, 2 left child, 3 its child, 4 that node's child, then back up to 5, then 6 the right child and 7 its child.
The walk goes down the left branch, then comes back for the right.

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. 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. 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. 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.

TypeScriptcollectDepthFirst
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. 1

    Enter 2 and go left. 1 has no left child, so the walk records 1 before it records anything above it.

  2. 2

    1 has no right child either. The walk returns to 2 and records 2. The list so far is 1, then 2.

  3. 3

    The right child is 3. Its left child is empty, so 3 is recorded next.

  4. 4

    3 has no right child. The branch is finished. The values are [1, 2, 3].

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.

A lock means the problem opens after you create an account. Pair With Target is open to try without one.

The same tree drawn twice with visit numbers. Depth-first preorder visits 1 root, 2 left child, 3 its child, 4 that node's child, 5 the left child's other child, 6 the right child, 7 its child. Breadth-first visits 1 root, 2 and 3 the two children, 4, 5 and 6 the next level left to right, then 7 the deepest node.
One tree, two visit orders: down a branch, or across a level.

Start Learning.

Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.