Pattern

Depth-first search

Explore as far as possible along one branch before backtracking, used across trees, graphs, and grids.

What it is

Depth-first search walks a tree, graph, or grid by committing to one neighbor (or child) and going all the way down before trying the next one, either with explicit recursion or a manual stack. On a tree that recursion is the traversal itself; on a graph or grid you additionally track which nodes or cells you have already visited so you don't loop forever on a cycle. Most of the value is in what you compute on the way down (top-down: pass state to children) or on the way back up (bottom-up: return a value each call reports to its parent), not in the traversal order alone.

When it applies

Tells in the problem

The classic mistake

The most common failure is doing real work more than once because a value that should be computed bottom-up (post-order) gets recomputed at every level instead, turning an O(n) walk into O(n²) — checking a subtree's height from scratch at every node instead of returning it while you're already there. The fix is to have the recursive call return the value the parent needs (a height, an "is this side balanced," a "best downward path here"), so each subtree is visited once, and the parent only combines results. Notice this in yourself when you find you're calling a helper function inside another traversal function that walks the same nodes again.

Questions to start with

All 23 depth-first search questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.