Skip to content
TOPIC · 14 PROBLEMS · 5 PATTERNS

Graphs

Things connected to other things. Cities and roads, people and friendships, emails and the accounts they belong to.

How to spot a graph problem

“connected”Anything described as linked, neighbouring, or reachable from something else. A grid counts: each cell is next to four others.
“shares a…”Two things belong together if they share anything. Those links chain, so a group can grow through things that never meet.
“before / after”Dependencies between tasks. That is a directed graph waiting to be put in order.

Five patterns cover almost everything

BFS

O(V + E)

Explore in rings: everything one step away, then everything two steps away, and so on.

Reach for it when you need the fewest steps between two things, or several starting points spreading at once.Go deeper: BFS and DFS: same graph, different order

Union-Find

≈ O(1) per op

Keep each group as a tree with one root. Join two groups by pointing one root at the other.

Reach for it when links arrive one at a time and you keep asking “are these in the same group?”.Go deeper: Union-find: who belongs together

Dijkstra

O(E log V)

BFS with a heap: always expand the cheapest place you can reach next.

Reach for it when edges have costs and none of them are negative.Go deeper: Shortest paths with Dijkstra

The one template to memorise

Fine, one exception. Breadth-first search with a queue and a seen-set shows up so often it is worth knowing cold. Everything else on this page, understand instead.

solution.py
from collections import deque
def bfs(start, neighbours):
seen = {start}
queue = deque([start])
while queue:
node = queue.popleft()
for nxt in neighbours(node):
if nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return seen

Problems, easy to hard

Do them in order the first time
#ProblemPatternDifficultySolution
1Flood FillDFSEasyRead
2Number of IslandsBFS / DFSMediumRead
3Max Area of IslandDFSMediumRead
4Clone GraphDFS + hash mapMediumRead
5Rotting OrangesMulti-source BFSMediumRead
6Pacific Atlantic Water FlowDFS from the edgesMediumRead
7Course ScheduleTopological sortMediumRead
8Course Schedule IITopological sortMediumRead
9Number of ProvincesUnion-FindMediumRead
10Redundant ConnectionUnion-FindMediumRead
11Accounts MergeUnion-FindMediumRead
12Network Delay TimeDijkstraMediumRead
13Word LadderBFSHardRead
14Swim in Rising WaterDijkstraHardRead
Next upDynamic programmingBacktracking