Topic · 7 patterns
Graphs patterns
Model the problem as nodes and edges first; the algorithm follows from what you're asked. BFS and DFS cover reachability, components and unweighted shortest paths, topological sort orders dependencies, union-find tracks groups as they merge, Dijkstra, Bellman-Ford and Floyd-Warshall find weighted shortest paths, and a minimum spanning tree connects everything at the least cost.
The patterns
Graph BFS / DFS
O(V + E)
Explore with a queue (BFS) or recursion/stack (DFS), marking visited so you never revisit a node.
Spot it: Grid or graph: islands, flood fill, regions, clone, reachability, or fewest steps on an unweighted / implicit graph.
Learn first: Tree BFS (Level Order), Tree DFS (Paths & Recursion)
Topological Sort
O(V + E)
Repeatedly take nodes with in-degree 0 (Kahn's), or DFS and emit on the way out; a cycle means no ordering.
Spot it: Prerequisites, dependencies, build order on a DAG; cycle detection in a directed graph; DP over a DAG; order from comparisons (alien dictionary).
Learn first: Graph BFS / DFS
Union-Find (Disjoint Set)
~O(α(n))
Each set has a representative; union merges two roots, find returns a root. Path compression + union by rank keep it near-constant.
Spot it: Connectivity with only additions: count components, group equivalents (accounts, equations), redundant edge in an undirected graph, Kruskal.
Dijkstra (Weighted Shortest Path)
O(E log V)
Greedily expand the closest unfinalized node using a min-heap keyed by distance-so-far.
Spot it: Min time/cost/effort on a weighted graph or grid with non-negative weights; minimax paths; max-probability paths (weights <= 1).
Learn first: Graph BFS / DFS, Top-K Elements
Bellman-Ford
O(V · E)
Relax every edge V−1 times; the k-stops variant just caps the number of relaxation rounds at k+1.
Spot it: Shortest path with negative edge weights, detect a negative cycle, or cheapest path using at most K edges / stops.
Learn first: Dijkstra (Weighted Shortest Path)
Floyd-Warshall
O(V³)
For every intermediate node k, test whether routing i→k→j beats the current i→j distance.
Spot it: Shortest paths or reachability between all pairs on a small graph: V up to ~400-500, or a small state graph like 26 letters.
Learn first: 1D / Fibonacci-style
Minimum Spanning Tree
O(E log V)
Kruskal: sort edges, add the cheapest that doesn't form a cycle (union-find). Prim: grow from a node via a heap.
Spot it: Connect all points/cities at minimum total cost, or the minimax (bottleneck) edge between two vertices — it lies on the MST.
Learn first: Union-Find (Disjoint Set), Greedy
Which one? Match the signal
| If the problem says | Reach for |
|---|---|
| Grid/graph: islands, flood fill, connected regions, clone, unweighted shortest path | Graph BFS / DFS |
| Prerequisites / dependencies / build order on a DAG; "can you finish?" | Topological Sort |
| Connectivity / "number of components" / merge groups / redundant edge | Union-Find |
| Weighted shortest path, non-negative weights (min time/effort/cost) | Dijkstra |
| Shortest path with negative weights, or "cheapest within at most k stops" | Bellman-Ford |
| Shortest paths between ALL pairs of nodes (small graph) | Floyd-Warshall |
| Connect every node at minimum total cost | MST (Kruskal/Prim) |
Easy to confuse
Reconstruct Itinerary looks like Graph BFS / DFS, but it’s Eulerian Path / Circuit (Hierholzer)
Every ticket (edge) must be used exactly once: Hierholzer, not plain DFS with backtracking.
Cheapest Flights Within K Stops looks like Dijkstra (Weighted Shortest Path), but it’s Bellman-Ford
The stop limit invalidates per-vertex optimality; k+1 Bellman-Ford rounds (or Dijkstra over (city, stops)).
Path with Maximum Probability looks like Bellman-Ford, but it’s Dijkstra (Weighted Shortest Path)
Multiplying probabilities <= 1 never increases a path's value, so Dijkstra with a max-heap is valid.
Path With Minimum Effort looks like Graph BFS / DFS, but it’s Dijkstra (Weighted Shortest Path)
Cost is the max edge on the path: minimax Dijkstra (or binary search + BFS, or union-find).
Swim in Rising Water looks like Graph BFS / DFS, but it’s Dijkstra (Weighted Shortest Path)
Minimax over cell heights; plain BFS ignores the cost.
Longest Increasing Path in a Matrix looks like Grid / Matrix DP, but it’s Topological Sort
Moves go in four directions, so there is no row-major order; the strict increase makes a DAG for memo DFS / Kahn.
Used together
Binary Search on the Answer + Graph BFS / DFS
When: minimise the maximum height/effort along a path. Minimax path costs become reachability at a threshold.
Offline Query Processing + Union-Find (Disjoint Set)
When: queries 'connected using edges with weight < limit'; reverse deletions. Each query asks connectivity under a weight limit; sorted processing makes it monotone.
Minimum Spanning Tree + Union-Find (Disjoint Set) + Greedy
When: connect all nodes at minimum cost. Kruskal is the canonical three-way composition.
Topological Sort + 1D / Fibonacci-style
When: longest path / number of paths in a DAG; longest increasing path in a grid. DP needs an acyclic evaluation order.
Graph BFS / DFS
- Flood FillEasy
- Number of IslandsMedium
Topological Sort
- Course ScheduleMedium
- Course Schedule IIMedium
Union-Find (Disjoint Set)
- Number of ProvincesMedium
Dijkstra (Weighted Shortest Path)
- Shortest Routes IMedium
- Network Delay TimeMedium
Bellman-Ford
- Network Delay TimeMedium
- Cheapest Flights Within K StopsMedium
Floyd-Warshall
- Find the City With the Smallest Number of Neighbors at a Threshold DistanceMedium
- Shortest Routes IIMedium
Minimum Spanning Tree
- Road ReparationMedium
Further reading
- Graph Theory playlistWilliam Fiset
Best visual explanations: BFS/DFS, topo sort, Dijkstra, Bellman-Ford, MST, flows.
- Graph TraversalUSACO Guide
BFS/DFS and connected components with graded problems.
- Disjoint Set Unioncp-algorithms
Path compression + union by size, with applications.
- Dijkstracp-algorithms
Proof plus the priority-queue implementation you will actually write.
- Topological sortingcp-algorithms
DFS-based topo order; pair with Kahn's for interviews.
- Shortest paths visualizerVisuAlgo
Step through Bellman-Ford and Dijkstra on your own graphs.
- Graph cheatsheetTech Interview Handbook
Interview-grade graph representation and problem list.