Pattern

Graph traversal

Model entities as nodes and relationships as edges, then traverse, order, or measure the resulting graph.

What it is

A graph problem asks you to reason about connections rather than sequences: nodes and the edges between them, which may be directed or undirected, weighted or not. Most of these questions are really "is this the graph in disguise" puzzles — a grid of cells, a list of words, or a set of equations all turn into an implicit graph once you name the nodes and the adjacency rule. Once you see the graph, the algorithm is usually one of a handful of standard traversals: BFS for shortest paths in unweighted graphs, DFS or Kahn's algorithm for ordering and cycle detection, Dijkstra when edges carry non-negative weights.

When it applies

Tells in the problem

The classic mistake

The most common failure is choosing the wrong unit for "distance". Interviewers report seeing candidates run BFS over the literal input elements (stops, characters, cells) when the quantity being minimized is something else entirely — the number of buses boarded, not stops visited; the bottleneck elevation on a path, not its length. The code still compiles and passes tiny examples because on small graphs the wrong unit and the right one often agree, but it falls apart or times out once routes overlap heavily or the grid gets large. Catch this by writing one sentence before coding: "a node in my graph represents ___, and one step means ___" — if that sentence doesn't match what the problem asks you to minimize, the graph is modeled wrong.

Questions to start with

All 26 graph traversal 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.