Graph traversal patterns for coding interviews
Graph traversal questions come down to choosing between breadth-first search, which explores in rings of equal distance and finds shortest paths when every step costs the same, and depth-first search, which follows one path to the end and suits reachability, components and cycle checks. Two variants cover most of the rest: multi-source BFS, which starts from many points at once, and topological ordering for tasks with prerequisites.
By Evin JohnPublished 7 min read
Recognizing a graph problem
Many graph questions never say "graph". Courses with prerequisites, words that differ by one letter, cells in a map, accounts that share an email, and servers that can call each other are all nodes with edges. The first step is to say what the nodes and edges are, and whether edges have a direction or a weight. That decision picks the algorithm. A grid is a graph whose edges are implied by position, which is why Number of Islands is a graph problem, and a tree is a graph with no cycles, which is why Binary Tree Level Order Traversal is a BFS.
| Question | Tool | Why |
|---|---|---|
| Fewest steps between two points, every step costs the same | BFS | It reaches nodes in order of distance |
| Distance from the nearest of many starting points | Multi-source BFS | All sources start in the queue at distance 0 |
| Is B reachable from A? How many separate groups? | DFS or BFS | Either visits everything connected |
| Order tasks so prerequisites come first | Topological sort | Repeatedly take a task with no remaining prerequisites |
| Cheapest path when edges have different costs | Dijkstra (heap) | BFS order is wrong when weights differ |
| Groups that merge as connections arrive | Union-find | Near-constant merges without re-traversing |
Template: BFS for shortest unweighted paths
Put the start in a queue with distance 0. Pop a node, and for each neighbor not yet seen, record its distance as one more and push it. Mark nodes as seen when you push them, not when you pop them; otherwise the same node can enter the queue several times.
from collections import deque
def bfs_distances(graph, start):
dist = {start: 0}
queue = deque([start])
while queue:
node = queue.popleft()
for nxt in graph[node]:
if nxt not in dist: # mark when queued
dist[nxt] = dist[node] + 1
queue.append(nxt)
return distfunction bfsDistances(graph, start) {
const dist = new Map([[start, 0]]);
const queue = [start];
for (let head = 0; head < queue.length; head++) {
const node = queue[head];
for (const next of graph.get(node) ?? []) {
if (!dist.has(next)) {
dist.set(next, dist.get(node) + 1);
queue.push(next);
}
}
}
return dist;
}Template: DFS for components and reachability
DFS can be recursive, but an explicit stack avoids recursion limits on large inputs (Python's default limit is around a thousand frames). To count groups, start a traversal from every node that has not been seen yet; the number of starts is the number of components.
def count_components(graph):
seen = set()
count = 0
for root in graph:
if root in seen:
continue
count += 1
stack = [root]
seen.add(root)
while stack:
node = stack.pop()
for nxt in graph[node]:
if nxt not in seen:
seen.add(nxt)
stack.append(nxt)
return countVariant: multi-source BFS on a grid
Here is an example written for this page. A floor plan marks charging points with S, walls with # and open floor with a dot. For every open cell, how many steps is it to the nearest charging point? Running a BFS from each charger separately repeats work. Instead, put every charger in the queue at distance 0 and run one BFS; each cell is reached first by its nearest charger. The same idea answers "how many minutes until the spread reaches every cell" questions.
from collections import deque
def nearest_source(grid):
rows, cols = len(grid), len(grid[0])
dist = [[-1] * cols for _ in range(rows)]
queue = deque()
for r in range(rows):
for c in range(cols):
if grid[r][c] == "S":
dist[r][c] = 0
queue.append((r, c))
while queue:
r, c = queue.popleft()
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if (0 <= nr < rows and 0 <= nc < cols
and grid[nr][nc] != "#" and dist[nr][nc] == -1):
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
return distVariant: topological order for prerequisites
Given tasks numbered 0 to n - 1 and pairs (a, b) meaning a must happen before b, count each task's unmet prerequisites. Start with every task that has none. Each time you complete a task, reduce the count of the tasks that depended on it, and queue any that reach zero. If some tasks never reach zero, the rules contain a cycle and no valid order exists. This is Kahn's algorithm.
from collections import deque
def topo_order(n, edges):
graph = [[] for _ in range(n)]
indegree = [0] * n
for a, b in edges: # a must come before b
graph[a].append(b)
indegree[b] += 1
queue = deque(i for i in range(n) if indegree[i] == 0)
order = []
while queue:
node = queue.popleft()
order.append(node)
for nxt in graph[node]:
indegree[nxt] -= 1
if indegree[nxt] == 0:
queue.append(nxt)
return order if len(order) == n else Nonefunction topoOrder(n, edges) {
const graph = Array.from({ length: n }, () => []);
const indegree = new Array(n).fill(0);
for (const [a, b] of edges) { graph[a].push(b); indegree[b]++; }
const queue = [];
for (let i = 0; i < n; i++) if (indegree[i] === 0) queue.push(i);
for (let head = 0; head < queue.length; head++) {
for (const next of graph[queue[head]]) {
if (--indegree[next] === 0) queue.push(next);
}
}
return queue.length === n ? queue : null; // null: there is a cycle
}Example problems to practice
- [Number of Islands](/coding-problems/number-of-islands). Components on a grid; flood fill from each unvisited land cell.
- [Binary Tree Level Order Traversal](/coding-problems/binary-tree-level-order-traversal). BFS that processes the queue one level at a time.
- Nearest charger, nearest exit, time to spread. Multi-source BFS, as above.
- Course or build order. Topological sort, returning an order or reporting a cycle.
- Word ladder. Words are nodes, one-letter changes are edges, BFS gives the fewest changes.
- Cheapest flight or network delay. Weighted edges, so switch to Dijkstra with a priority queue; see the heap and priority queue pattern.
Complexity
| Algorithm | Time | Extra space |
|---|---|---|
| BFS or DFS over the whole graph | O(V + E) | O(V) for seen and the queue or stack |
| Multi-source BFS on a grid | O(rows × cols) | O(rows × cols) |
| Topological sort (Kahn) | O(V + E) | O(V + E) for the adjacency list |
| Dijkstra with a binary heap | O((V + E) log V) | O(V + E) |
Common mistakes
- Marking visited on pop in BFS. Nodes get queued many times, which wastes time and can break distance counts in some variants.
- Using BFS for weighted shortest paths. It is only correct when every edge costs the same.
- Deep recursion. Recursive DFS on a 1,000 by 1,000 grid can overflow the call stack; use an explicit stack.
- Forgetting disconnected parts. Start a traversal from every unvisited node, not just node 0.
- Building the graph in the wrong direction for prerequisites. Decide whether an edge means "before" or "after" and say it.
How to explain it out loud
Fictional example
- Candidate
- The floor plan is a graph: each open cell is a node and its four neighbors are edges, all with the same cost, so shortest distance means BFS.
- Candidate
- Running one BFS per charger would be chargers times cells. If I put all chargers in the queue at distance zero, the first time any cell is reached is from its nearest charger, so one pass is enough.
- Candidate
- Every cell is queued at most once, so it is linear in the number of cells, with the distance grid as extra space.
Depth-first search with an undo step is backtracking, and counting right-and-down paths across a grid is a dynamic programming question rather than a search. All walkthroughs are on the coding problems hub.
Practicing with Natively
Natively runs on Mac and Windows and, during practice, can read a graph problem from a screenshot, suggest how to model the nodes and edges, and draw a small diagram of the approach inside its answer. Saved transcripts of mock rounds help you check whether you named the representation before coding. See the AI interview assistant.
Questions people ask
When should you use BFS instead of DFS?
Use BFS when you need the fewest steps and every step costs the same, or when you process something level by level. Use DFS for reachability, counting connected groups and cycle checks.
What is multi-source BFS?
A breadth-first search that starts with several nodes in the queue at distance zero. Each node is first reached from its nearest source, so one pass gives every node's distance to the closest source.
How does topological sort detect a cycle?
In Kahn's algorithm, tasks are taken once all their prerequisites are done. If some tasks are never taken, their prerequisites form a loop, so no valid order exists.
What is the time complexity of BFS and DFS?
O(V + E) for V nodes and E edges, because each node is visited once and each edge is examined once or twice. Extra space is O(V) for the visited set and the queue or stack.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
