Graphs · Lesson
Graphs, explained: BFS, DFS, topological sort and every pattern
Learn graphs from scratch: BFS, DFS, union find, cycles, topological sort, Dijkstra and MST, with templates in Java, Python, C++ and JavaScript.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
What a graph is
A graph is a set of nodes joined by edges. Edges can be one-way (directed: a course and its prerequisite) or two-way (undirected: two friends). They can also carry a weight, like a distance or a price.
Interview graphs rarely arrive as a graph object. They hide as a grid (each cell is a node, its 4 neighbours are edges), a list of pairs, a dependency list, or a rule like "words that differ by one letter". The first step is always the same: decide what a node is and what an edge is.
Store the graph as an adjacency list: for every node, the list of its neighbours. It takes O(V + E) space and lets you visit every neighbour of a node in time proportional to how many it has.
BFS or DFS?
Both visit every reachable node once, so both cost O(V + E). The difference is the order:
- BFS (a queue) goes out in rings: first everything 1 edge away, then 2, then 3. So the first time it reaches a node is along a shortest path, counted in edges.
- DFS (recursion or a stack) goes as deep as it can, then backs up. That makes it natural for exploring a whole component, finding cycles and anything that needs "finished" order.
In both, keep a visited mark so no node is processed twice. Without it, any cycle makes the search run forever.
How to pick the pattern
- Fewest steps, every move costs the same: BFS. Many starting points at once: multi-source BFS.
- Edges with different non-negative costs: Dijkstra.
- Count or group the pieces: DFS per component, or union-find when edges arrive one by one.
- Tasks with prerequisites, an order to respect: topological sort. If no order exists, there is a cycle.
- Connect everything as cheaply as possible: minimum spanning tree.
- An answer for every node of a tree: re-rooting DP instead of n separate searches.
What it costs
| Operation | Time | Space |
|---|---|---|
| Build an adjacency list | O(V + E) | O(V + E) |
| BFS or DFS over the whole graph | O(V + E) | O(V) |
| Topological sort (Kahn) | O(V + E) | O(V) |
| Union-find, per find or union | almost O(1) amortised | O(V) |
| Dijkstra with a binary heap | O((V + E) log V) | O(V + E) |
| Kruskal's minimum spanning tree | O(E log E) | O(V) |
Built into your language
int n = 4; int[][] edges = {{0, 1}, {1, 2}, {2, 3}};
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); } // undirected
Deque<Integer> q = new ArrayDeque<>(); // BFS queue
q.offer(0); q.poll();
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])); // min-heap of {dist, node}
pq.offer(new int[]{0, 0}); pq.poll(); from collections import defaultdict, deque
import heapq
adj = defaultdict(list)
for u, v in [(0, 1), (1, 2), (2, 3)]:
adj[u].append(v)
adj[v].append(u) # undirected
q = deque([0]); q.popleft() # BFS queue, O(1) at both ends
pq = []
heapq.heappush(pq, (0, 0)) # min-heap of (dist, node)
d, u = heapq.heappop(pq) int n = 4;
vector<vector<int>> adj(n);
adj[0].push_back(1); adj[1].push_back(0); // undirected edge 0-1
queue<int> q; q.push(0); q.front(); q.pop(); // BFS queue
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq; // min-heap of {dist, node}
pq.push({0, 0});
auto [d, u] = pq.top(); pq.pop(); const n = 4;
const adj = Array.from({ length: n }, () => []); // not new Array(n).fill([]): that shares one array
adj[0].push(1); adj[1].push(0); // undirected edge 0-1
const q = [0]; let head = 0; // queue: read q[head++], since shift() is O(n)
const first = q[head++];
// there is no built-in priority queue: write a small binary heap (see the Dijkstra template) Mistakes everyone makes
- Marking a node visited when you pop it in BFS instead of when you push it: the same node enters the queue many times.
- Starting the search only from node 0. A graph can have several components, so loop over every node and start a search from each unvisited one.
- Using BFS when the edges have different weights. BFS counts edges, not cost: use Dijkstra.
- Adding a directed edge in both directions, or forgetting to add an undirected edge both ways.
- Deep recursion on big inputs: a path of 10^5 nodes can overflow the call stack (Python's default limit is 1000 frames). Use an explicit stack or BFS when that can happen.
Lesson done
Start pattern 1: BFS and DFS: walking a graph →The 14 patterns, in order
Each one: the idea and template, its variations with a worked example, then problems for you to solve.
- 1 BFS and DFS: walking a graph Build an adjacency list, then visit every reachable node once. BFS uses a queue and goes out level by level; DFS goes deep first with recursion or a stack. 5 variations · 11 problems
- 2 Grids as graphs: flood fill and islands Every cell is a node and its 4 neighbours are its edges. A DFS from a cell floods its whole region; marking cells in the grid itself replaces the visited set. 6 variations · 9 problems
- 3 Connected components and union-find Count or group the separate pieces of a graph. A DFS from every unvisited node works when the graph is fixed; union-find merges groups in almost O(1) when edges arrive one at a time. 5 variations · 12 problems
- 4 BFS for the shortest path When every move costs 1, BFS reaches each node first along a shortest path. Count the levels until you pop the target. The node can be a cell, a word, a whole board or a cell plus extra state. 5 variations · 12 problems
- 5 The complement trick: search from the border Finding what is trapped is hard; finding what escapes is easy. DFS from every border cell to mark the safe cells, then everything left unmarked is the answer. 1 variation · 1 problem
- 6 Multi-source BFS: spread from many starts at once Put every starting cell in the queue before the first step. The BFS then spreads from all of them together, and each cell is reached first by its nearest source. 4 variations · 8 problems
- 7 Cycle detection and bipartite graphs Undirected graph: a cycle is a visited neighbour that is not the node you came from. Directed graph: a cycle is an edge back to a node still on the current DFS path. Two-colouring finds odd cycles. 4 variations · 6 problems
- 8 Topological sort: an order that respects every dependency Count how many edges point into each node. Nodes with none can go first; removing them frees their neighbours. If some nodes never reach zero, there is a cycle and no valid order. 4 variations · 12 problems
- 9 Dijkstra's algorithm: shortest paths with weights Always expand the closest node not yet settled, using a min-heap. With non-negative weights, the first time a node is popped its distance is final. Skip stale heap entries. 4 variations · 7 problems
- 10 Eulerian path: use every edge once (Hierholzer's algorithm) Walk along unused edges until you get stuck, then back up. Each node you back out of goes at the front of the route. Reversed, that finish order uses every edge exactly once. 1 variation · 1 problem
- 11 Candidate elimination: one pass to rule people out Every question "does a know b?" rules out one person. One pass leaves a single candidate; a second pass checks that the candidate really is the celebrity. 1 variation · 1 problem
- 12 Re-rooting DP: the answer for every root in O(n) Solve the problem for one root with a DFS. Then move the root across one edge at a time: only that edge changes, so each neighbour's answer comes from its parent's in O(1). 2 variations · 2 problems
- 13 Minimum spanning tree: Kruskal's algorithm Sort the edges by cost and add each one unless it would close a loop (union-find tells you). After n − 1 edges every node is connected as cheaply as possible. 1 variation · 2 problems
- 14 Degree counting: answers without a search Some questions only need how many edges touch each node. Count in-degrees (or check two edges) and the answer falls out with no BFS or DFS at all. 2 variations · 2 problems