Skip to content

Graphs

Reach for it when the problem says

  • Grids
  • networks
  • dependencies
  • shortest path
  • islands
Solved
0/33Solved
Problems
33Problems
Variants
6Variants

Problems

6 variants

Grid flood fill

0 of 5 solved

BFS shortest path

0 of 7 solved

Topological sort

0 of 3 solved

Union-find

0 of 4 solved

Weighted graphs

0 of 5 solved

Graph traversal

0 of 9 solved

Pattern guide

Graph problems are the largest single family in interviews, and they rarely say "graph". They say islands, courses, flights, accounts, oranges or words. The skill that pays off is seeing the nodes and edges inside the story, because once you do, five or six well-known templates cover almost everything.

What it is

A graph is a set of nodes (also called vertices) joined by edges. Edges can be undirected (a road you can drive both ways) or directed (a one-way flight, a prerequisite), and they can be unweighted or carry a weight (a price, a delay, a height difference). V is the number of nodes and E the number of edges.

Almost every graph algorithm is the same loop with a different container. You keep a frontier of nodes you have discovered but not yet expanded, and a visited set so that cycles cannot trap you. Pop a node, look at its neighbours, add the new ones to the frontier. A stack gives you DFS (depth-first search), a queue gives you BFS (breadth-first search), and a min-heap gives you Dijkstra.

BFS from S on an unweighted graph
S0ABCDT

currentwaitingdone

Start at S with distance 0. Mark it visited as it enters the queue, not when it leaves.

1/5

That last sentence is the reason BFS matters: in an unweighted graph, the first time BFS touches a node is along a shortest path. DFS gives no such promise, but it is simpler to write and is all you need when the question is only "can I reach it?" or "how many groups are there?".

Quick check
In BFS, why mark a node visited when you push it rather than when you pop it?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat it suggests
"grid", "map", "island", "region", "up, down, left or right"A grid graph: each cell is a node with up to four edges
"connected", "group", "province", "component"Count or label connected components (DFS or union-find)
"minimum number of steps", "shortest", "fewest moves", "minutes until"BFS on an unweighted graph
"nearest", "from every gate", "all rotten oranges at once"Multi-source BFS: start with every source in the queue
"prerequisite", "before", "depends on", "order of tasks"Directed graph plus topological sort
"cycle", "redundant", "valid tree"Cycle detection: union-find for undirected, colours or Kahn's for directed
"cheapest", "price", "delay", "cost", "effort" with numbers on edgesWeighted shortest path: Dijkstra, or Bellman-Ford with a hop limit
"connect all", "minimum total cost to connect"Minimum spanning tree (Prim or Kruskal)
"deep copy", "clone"Traversal plus a map from original node to copy

Constraint clues

ConstraintWhat it tells you
Grid up to 300 x 300 or 250 x 250Up to 90,000 cells: O(rows · cols) only. Prefer an explicit stack to deep recursion
n <= 2 * 10^5 nodes and edgesO(V + E) with an adjacency list; a V by V matrix would not fit
n <= 100 or n <= 200 given as a matrixO(n²) or even O(n³) is fine; the input itself is n²
Weights >= 0Dijkstra is safe
A limit like "at most k stops"Plain Dijkstra breaks; use Bellman-Ford rounds or a (node, stops) state
edges.length == n - 1 or == nA tree, or a tree plus exactly one extra edge
points.length <= 1000, every pair is an edgeA dense graph: array-based Prim's in O(n²)

Input and output shape clues

ShapeLikely sub-pattern
2D grid in, a count or an area outGrid flood fill
Grid or word list in, a number of steps outBFS shortest path
Edge list or adjacency list in, true/false or a count outGraph traversal or union-find
Pairs [a, b] meaning "b before a", an order outTopological sort
Edges arriving one by one, "which edge" or "how many groups" outUnion-find
Triples [u, v, w] or a height grid, a cost outWeighted graphs

Looks like it but isn't

  • Grid does not mean dynamic programming. If movement is only right and down, a DP table works. If you can move in all four directions, paths can loop back, there is no fill order, and you need a graph search.
  • Trees are graphs with a guarantee. If the input is an edge list with a possible cycle, tree recursion without a visited set will loop forever. Clone Graph is the classic trap.
  • "Shortest" with weights is not BFS. BFS counts edges. The moment edges have different costs, a two-hop detour can beat one slow direct edge, and you need Dijkstra.
  • Greedy nearest-neighbour is not an MST. Linking each point to its closest neighbour can leave separate clusters. Prim's and Kruskal's are greedy, but in a specific, provably correct way.
Match the pairs0/5 matched

Match each prompt phrase to the tool it points at.

Choose an item, then its match on the other side.

The sub-patterns

Grid flood fill

When it applies: the input is a grid and the question is about connected regions: count them, measure them, recolour them, or find the cells that can reach an edge. Each cell is a node, and its four side neighbours are its edges. You never build an adjacency list; four (dr, dc) offsets and a bounds check do the job.

The move is always the same. Scan every cell. When you meet a cell that starts a new region, flood it with DFS or BFS and mark what you reach, often by overwriting the grid itself. For "which cells can reach the border" questions, flip it around and flood from the border inward.

Flood fill counts islands
1100
1001
0011
1000

Scan from the top-left. (0,0) is land nobody has visited: island 1. Start a flood here.

1/4
Pythonflood_fill_template.py
def count_regions(grid: list[list[str]]) -> int: rows, cols = len(grid), len(grid[0]) count = 0 for r in range(rows): for c in range(cols): if grid[r][c] != "1": continue count += 1 grid[r][c] = "0" # mark when you push stack = [(r, c)] while stack: cr, cc = stack.pop() for nr, nc in ((cr + 1, cc), (cr - 1, cc), (cr, cc + 1), (cr, cc - 1)): if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1": grid[nr][nc] = "0" stack.append((nr, nc)) return count print(count_regions([list("1100"), list("1001"), list("0011"), list("1000")])) # 3
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(rows · cols) time, O(rows · cols) space for the stack in the worst case (one huge region).

Best-known problems: Number of Islands, Max Area of Island, Flood Fill, Surrounded Regions, Pacific Atlantic Water Flow.

BFS shortest path

When it applies: you need the fewest steps, moves or minutes, and every step costs the same. BFS explores in rings of equal distance, so the first time it reaches a cell or word, that is the shortest distance. Process the queue one layer at a time when the answer is "how many layers" (minutes, steps).

The most useful twist is multi-source BFS: when the question says "nearest of many" (nearest gate, every rotten orange at once), put every source in the queue at distance 0 before you start. One BFS then gives every cell its distance to the closest source.

Multi-source BFS: rotting oranges
211
110
011

Minute 0. The only rotten orange (2) seeds the queue. Count fresh oranges up front: 6.

1/5
Pythonbfs_layers_template.py
from collections import deque def min_steps(grid: list[list[int]], sources: list[tuple[int, int]]) -> list[list[int]]: rows, cols = len(grid), len(grid[0]) dist = [[-1] * cols for _ in range(rows)] queue = deque() for r, c in sources: # every source starts at distance 0 dist[r][c] = 0 queue.append((r, c)) while queue: r, c = queue.popleft() for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)): if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0 and dist[nr][nc] == -1: dist[nr][nc] = dist[r][c] + 1 queue.append((nr, nc)) return dist walls = [[0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 0, 0]]for row in min_steps(walls, [(0, 0), (2, 3)]): print(row)
Output
Press Run (⌘ Enter) to see what happens.

The TypeScript version uses a growing array with a head index instead of shift(), because shift() is O(n) and turns BFS quadratic on big inputs.

Complexity: O(V + E), which on a grid is O(rows · cols). For word ladders, generating neighbours costs 26 · L per word.

Best-known problems: Rotting Oranges, Walls and Gates, Word Ladder, Shortest Path in Binary Matrix, Nearest Exit from Entrance in Maze.

Predict the outputPython

What does this print?

from collections import deque

graph = {0: [1, 2], 1: [3], 2: [3, 4], 3: [5], 4: [5], 5: []}
dist = {0: 0}
queue = deque([0])
while queue:
  node = queue.popleft()
  for nxt in graph[node]:
      if nxt not in dist:
          dist[nxt] = dist[node] + 1
          queue.append(nxt)
print(dist[5], len(dist))
Need a nudge? Hints walk you through it.

Graph traversal

When it applies: the graph is given explicitly (an edge list, an adjacency list, an adjacency matrix, or node objects) and the question is about reachability, components, copying, colouring or walking every edge. You build an adjacency list, then run DFS or BFS with a visited set. What you do at each node is the part that changes.

  • Reachability: can you get from s to t? Can room 0 reach every room?
  • Components: count how many traversals you have to start (Number of Provinces).
  • Copying: keep a map from original node to copy (Clone Graph).
  • Colouring: give neighbours opposite colours and look for a clash (Is Graph Bipartite?).
  • Edge tags: store extra data on each edge, like a direction flag (Reorder Routes) or a ratio (Evaluate Division).
  • Every edge once: post-order DFS that writes a node down when it runs out of edges (Reconstruct Itinerary).
Two-colouring with DFS
0A1234

currentwaitingdone

Colour node 0 with A. Its neighbours are now forced to be B.

1/4
Pythontraversal_template.py
def build(n: int, edges: list[list[int]]) -> list[list[int]]: graph = [[] for _ in range(n)] for a, b in edges: graph[a].append(b) graph[b].append(a) # undirected: add both ways return graph def components(n: int, edges: list[list[int]]) -> int: graph = build(n, edges) seen = [False] * n count = 0 for start in range(n): if seen[start]: continue count += 1 # a new traversal = a new component seen[start] = True stack = [start] while stack: node = stack.pop() for nxt in graph[node]: if not seen[nxt]: seen[nxt] = True stack.append(nxt) return count print(components(6, [[0, 1], [1, 2], [3, 4]])) # 3: {0,1,2}, {3,4}, {5}
Output
Press Run (⌘ Enter) to see what happens.

Complexity: O(V + E) time, O(V + E) space for the adjacency list. With an adjacency matrix it is O(V²), because reading a node's row costs V.

Best-known problems: Clone Graph, Number of Provinces, Keys and Rooms, Is Graph Bipartite?, Evaluate Division, Reconstruct Itinerary.

Quick check
A bipartite check runs DFS from node 0 only and returns true if it finds no clash. Which input breaks it?
Need a nudge? A hint rules out a wrong answer.

Topological sort

When it applies: a directed graph of dependencies ("b before a") where you must produce an order that respects every edge, or decide that no order exists. An order exists exactly when the graph has no cycle (a DAG, directed acyclic graph).

Kahn's algorithm is the version to reach for first. Count each node's in-degree (how many arrows point into it). Every node with in-degree 0 has nothing blocking it, so queue it. Pop a node, append it to the order, and lower the in-degree of everything it points at; anything that drops to 0 joins the queue. If the order ends up shorter than the number of nodes, the leftovers sit on a cycle.

Kahn's algorithm on course prerequisites
0in 01in 12in 13in 24in 1

currentwaitingdone

Count in-degrees. Only course 0 has none, so it is the only one in the queue.

1/5
Pythonkahn_template.py
from collections import deque def topo_order(n: int, pairs: list[list[int]]) -> list[int]: after = [[] for _ in range(n)] indegree = [0] * n for later, before in pairs: # [a, b] means b comes before a after[before].append(later) indegree[later] += 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 after[node]: indegree[nxt] -= 1 if indegree[nxt] == 0: queue.append(nxt) return order if len(order) == n else [] # [] means a cycle print(topo_order(5, [[1, 0], [2, 0], [3, 1], [3, 2], [4, 3]]))print(topo_order(2, [[1, 0], [0, 1]]))
Output
Press Run (⌘ Enter) to see what happens.

The alternative is DFS with three colours (unvisited, in progress, done): reaching an "in progress" node means a cycle, and appending nodes when they finish, then reversing, gives a topological order. Both are O(V + E); Kahn's is easier to get right under pressure.

Complexity: O(V + E) time and space.

Best-known problems: Course Schedule, Course Schedule II, Alien Dictionary.

Put it in order5 steps

Put the steps of Kahn's algorithm in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Union-find

When it applies: you care about which group each node is in, edges arrive as a list (often one at a time), and you want to merge groups or detect the edge that closes a cycle in an undirected graph. Union-find (also called disjoint set union, DSU) keeps a parent array where each group is a little tree; the root names the group.

Two operations do everything. find(x) walks up to the root, and path compression shortcuts the walk so later finds are nearly instant. union(a, b) links one root under the other. If find(a) == find(b) before a union, a and b were already connected, so the edge between them is redundant: it closes a cycle.

Union-find parent array, nodes 0 to 5
0
0
1
1
2
2
3
3
4
4
5
5
groups = 6

Every node is its own parent: six groups of one. Index is the node, value is its parent.

1/5
Pythonunion_find_template.py
class DSU: def __init__(self, n: int): self.parent = list(range(n)) self.groups = n def find(self, x: int) -> int: while self.parent[x] != x: self.parent[x] = self.parent[self.parent[x]] # path compression x = self.parent[x] return x def union(self, a: int, b: int) -> bool: ra, rb = self.find(a), self.find(b) if ra == rb: return False # already connected: this edge is a cycle self.parent[ra] = rb self.groups -= 1 return True dsu = DSU(6)for a, b in [[0, 1], [3, 2], [0, 3], [1, 3]]: print([a, b], "merged" if dsu.union(a, b) else "closes a cycle")print("groups:", dsu.groups)
Output
Press Run (⌘ Enter) to see what happens.

Complexity: each operation is O(α(n)), the inverse Ackermann function, which is at most 4 for any input you will ever see. So E edges cost about O(E). Add union by size or rank for the textbook guarantee; path compression alone is plenty in interviews.

Best-known problems: Number of Connected Components, Graph Valid Tree, Redundant Connection, Accounts Merge.

Weighted graphs

When it applies: edges carry a cost and you want the cheapest route, the route with the smallest worst step, or the cheapest way to connect everything. Three tools cover nearly every case:

SituationToolTime
Shortest path, weights >= 0Dijkstra with a min-heapO(E log V)
Path cost is the maximum edge or cell (effort, rising water)Dijkstra with max instead of +O(E log V)
A limit on the number of edges ("at most k stops")Bellman-Ford for k + 1 roundsO(k · E)
Connect every node as cheaply as possiblePrim's (dense) or Kruskal's with union-find (sparse)O(V²) or O(E log E)

Dijkstra's key fact: when all weights are non-negative, the unsettled node with the smallest tentative distance can never get cheaper, so you can settle it for good. A heap hands you that node in O(log V). Old heap entries for a node you already settled are simply skipped when popped.

Dijkstra from S
S0A4B1CT412172

currentwaitingdone

Settle S at 0. Tentative distances: A = 4, B = 1.

1/5
Pythondijkstra_template.py
import heapq def dijkstra(n: int, edges: list[list[int]], src: int) -> list[float]: graph = [[] for _ in range(n)] for u, v, w in edges: graph[u].append((v, w)) # directed; add (u, w) to graph[v] for undirected dist = [float("inf")] * n dist[src] = 0 heap = [(0, src)] while heap: d, node = heapq.heappop(heap) if d > dist[node]: continue # stale entry for nxt, w in graph[node]: if d + w < dist[nxt]: dist[nxt] = d + w heapq.heappush(heap, (dist[nxt], nxt)) return dist # S=0, A=1, B=2, C=3, T=4print(dijkstra(5, [[0, 1, 4], [0, 2, 1], [2, 1, 2], [1, 3, 1], [2, 4, 7], [3, 4, 2]], 0))
Output
Press Run (⌘ Enter) to see what happens.

In TypeScript interviews, say out loud that there is no standard heap: either write a 25-line binary heap, or use the O(V²) scan when V is small (a few thousand at most). Both are accepted answers.

Complexity: O(E log V) with a heap, O(V²) with the array scan. Bellman-Ford is O(k · E) with a hop limit and O(V · E) without one.

Best-known problems: Network Delay Time, Cheapest Flights Within K Stops, Path With Minimum Effort, Swim in Rising Water, Min Cost to Connect All Points.

Quick check
Why does plain Dijkstra give wrong answers for Cheapest Flights Within K Stops?
Need a nudge? A hint rules out a wrong answer.

Decision checklist

Ask these in order. The first "yes" usually names the sub-pattern.

  1. Is the input a grid and the question about regions? Grid flood fill.
  2. Do you need the fewest steps with every step costing the same? BFS shortest path (multi-source if there are many starts).
  3. Do edges say "before" or "depends on"? Topological sort.
  4. Are you merging groups, or hunting the edge that closes a cycle in an undirected graph? Union-find.
  5. Do edges or cells carry costs you add up, take the max of, or must connect cheaply? Weighted graphs.
  6. Otherwise: build an adjacency list and run a graph traversal, deciding what to do at each node.
Match the pairs0/6 matched

Match each problem to its sub-pattern.

Choose an item, then its match on the other side.

Traps

  • Marking visited too late. Mark when you push, not when you pop. Late marking queues duplicates and, in grid BFS, can produce wrong layer counts.
  • Forgetting both directions. For an undirected edge list, add b to a's list and a to b's list. Missing one makes half the graph unreachable.
  • Only starting from node 0. Components, bipartite checks and topological sorts must loop over every node, because the graph may be disconnected.
  • Recursion depth. A 300 by 300 grid of land is 90,000 nested calls. Python's default limit is 1000. Use an explicit stack or a queue.
  • queue.shift() in JavaScript. It is O(n), so BFS becomes O(n²). Use a head index into an array.
  • Same colour flood fill. In Flood Fill, if the new colour equals the old one, painted cells still match and the fill never ends. Return early.
  • BFS on weighted edges. BFS counts edges, not cost. If weights differ, use Dijkstra.
  • Off-by-one in counting. Word Ladder counts words, not steps, so it starts at 1. Shortest Path in Binary Matrix counts cells, so a 1 by 1 grid answers 1. Rotting Oranges with nothing fresh answers 0, not 1.

Edge cases to always test: an empty or single-node graph, a graph with no edges, a disconnected graph, a self-loop or two-node cycle, duplicate edges, and the largest input (for recursion depth).

Quick check
n = 4, edges = [[0, 1], [1, 2], [2, 0]]. A Graph Valid Tree solution only checks len(edges) == n - 1. What does it return, and is that right?
Need a nudge? A hint rules out a wrong answer.

How to talk it through

A model narration for Rotting Oranges: "Each cell is a node with four neighbours. Rot spreads from every rotten orange at once, one step a minute, so minutes are BFS layers from all the rotten oranges together. I'll queue every rotten orange, count fresh ones, and process one layer per minute, rotting neighbours and decrementing the count. When the queue empties, I return the minutes if nothing fresh is left, otherwise minus one. Each cell is queued once, so it's O(rows times cols)."

Key terms
Adjacency list
For each node, the list of its neighbours. O(V + E) space, the default way to store a sparse graph.
Connected component
A maximal group of nodes that can all reach each other. Counting islands or provinces is counting components.
Multi-source BFS
BFS that starts with every source in the queue at distance 0, giving each node its distance to the nearest source in one pass.
Topological order
An ordering of a directed graph's nodes where every edge points forward. It exists only when the graph has no cycle.
Union-find
A parent array that tracks groups. find returns a group's root, union merges two groups, and equal roots before a union reveal a cycle.
Dijkstra's algorithm
Shortest paths with non-negative weights: repeatedly settle the closest unsettled node using a min-heap. O(E log V).