Graphs
A graph is just things (nodes) and links between them (edges). Interview graphs are often disguised: a grid is a graph where each cell links to its 4 neighbors, and a list of prerequisite pairs is a graph where each pair is an edge.
When to reach for it
Section titled “When to reach for it”- The input is a grid and you must find regions, count groups or spread something outward.
- The input is a list of pairs (
[a, b]) describing relationships or dependencies. - You see words like “connected”, “reachable”, “island”, “network”, “prerequisite”, “order”.
- DFS (recursion or a stack) is enough to visit everything, count components or explore all paths.
- BFS (a queue) is required for shortest path in an unweighted graph and for anything measured in “levels”, “steps” or “minutes”. The first time BFS reaches a node is the shortest way there.
- “Can all tasks be done?” or “give a valid order” means cycle detection / topological sort.
Template
Section titled “Template”from collections import deque
# Build adjacency list from edges (skip for grids: neighbors are implicit)graph = {i: [] for i in range(n)}for a, b in edges: graph[a].append(b) # add graph[b].append(a) if undirected
def bfs(starts): seen = set(starts) # mark when ENQUEUED, not when popped queue = deque(starts) # several starts = multi-source BFS level = 0 while queue: for _ in range(len(queue)): # one pass = one level node = queue.popleft() for nxt in graph[node]: # grid: the 4 in-bounds neighbors if nxt not in seen: seen.add(nxt) queue.append(nxt) level += 1Three habits cover most bugs. Always keep a visited set (or mutate the grid) or you loop forever on cycles. Mark visited when you add to the queue. For a dependency order, count each node’s incoming edges and process nodes that reach zero (Kahn’s algorithm).
Problems in this guide
Section titled “Problems in this guide”- Number of Islands — flood fill each unvisited land cell
- Clone Graph — map each old node to its clone while traversing
- Course Schedule — detect a dependency cycle with topological sort
- Rotting Oranges — multi-source BFS, one level per minute