Shortest paths, flood fills, and connected components in arbitrary networks
175 problems·4 Easy·86 Medium·85 Hard
Pattern Study Guide & Cheat Sheet· O(V + E) visits every vertex and edge once · O(V) for queue and visited set
▼
Explore vertices and edges in arbitrary networks using BFS (for unweighted shortest paths) or DFS (for connectivity, cycle detection, and component exploration).
Core Invariant: Visited Set Invariant: A node must be marked visited AT THE MOMENT IT IS ENQUEUED (for BFS) or entered (for DFS). Marking on pop causes the same node to be enqueued multiple times exponentially.
Recognize it (Keywords & Signals)
Shortest path / minimum transformations in unweighted graph
Clone graph / serialize network
Connected components / bipartite graph check
Word ladder (transform word A to B)
Detect cycle in directed or undirected graph
When NOT to use
Weighted graph with varying edge costs (use Dijkstra for non-negative weights, Bellman-Ford for negative weights).
2.Choose traversal: BFS (`deque`) for shortest path; DFS (recursion) for exploration/cycles.
3.Initialize `visited = set([start_node])` and `queue = deque([(start_node, 0)])`.
4.While queue is not empty: pop `curr, dist`.
5.If `curr == target`, return `dist`.
6.For each `neighbor in graph[curr]`: if `neighbor not in visited`, mark `visited.add(neighbor)` and `queue.append((neighbor, dist + 1))`.
Watch for (Interview Traps)
Marking visited on pop instead of enqueue: causes catastrophic duplicate queue insertions and TLE
Directed vs undirected: adding bidirectional edges when edges are strictly directed
Not handling disconnected graph components (need a wrapper loop over all nodes `0..V-1`)
BFS Shortest Path (Unweighted Graph)
from collections import deque, defaultdict
def bfs_shortest_path(edges: list[list[int]], start: int, target: int) -> int:
# 1. Build adjacency list
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
# 2. Queue stores (current_node, distance)
queue = deque([(start, 0)])
visited = {start} # ALWAYS mark visited at enqueue time
while queue:
curr, dist = queue.popleft()
if curr == target:
return dist
for neighbor in graph[curr]:
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, dist + 1))
return -1 # Target unreachable
Cost
O(V + E) visits every vertex and edge once · O(V) for queue and visited set (Linear in graph size for adjacency list representation.)
Canonical problems
#127 Word Ladder:BFS finds shortest sequence of 1-letter word mutations
#133 Clone Graph:DFS/BFS with hash map mapping original node to cloned copy
#785 Is Graph Bipartite?:2-color BFS/DFS to verify no adjacent nodes share same color
#200 Number of Islands:Graph traversal over grid adjacency
What is the Graph Traversal (BFS & DFS) pattern in coding interviews?
Shortest paths, flood fills, and connected components in arbitrary networks It is categorized under Trees & Graphs and features 175 curated interview problems across Easy (4), Medium (86), and Hard (85) difficulties.
Which tech companies frequently test Graph Traversal (BFS & DFS)?
How do I master the Graph Traversal (BFS & DFS) pattern?
Start by studying the algorithmic strategy and template code, then practice Easy and Medium problems before attempting Hard problems under timed conditions.