Skip to content

Graphs

Graphs in under a minute

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.

  • 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.
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 += 1

Three 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).