Module 5 · Lesson 1 · ~25 min
Trees are a special case of graphs. Half of "tree" interview problems are graphs in disguise. This lesson is the picture you need: what a graph is, how to represent it, and the two traversals that solve everything.
A graph is a set of nodes (sometimes called vertices) and edges connecting pairs of them. Nodes can be cities and edges roads. Or people and friendships. Or web pages and links. Or files and dependencies.
Edges can be directed (a one-way street) or undirected (a friendship — symmetric). They can be weighted (the road has a length) or unweighted.
A dict mapping each node to a list of its neighbors. Compact for sparse graphs (few edges). O(V + E) space.
graph = {
'A': ['B', 'C'],
'B': ['D'],
'C': ['D'],
'D': [],
}
const graph = {
A: ['B', 'C'],
B: ['D'],
C: ['D'],
D: [],
};
// Or, for non-string keys:
// const graph = new Map([['A', ['B', 'C']], ...]);
const graph: Record<string, string[]> = {
A: ['B', 'C'],
B: ['D'],
C: ['D'],
D: [],
};
// Or: const graph: Map<string, string[]> = new Map([...]);
An n × n matrix where matrix[i][j] = 1 if there's an edge from i to j. O(V²) space — only worth it for dense graphs.
| Operation | Adjacency list | Adjacency matrix |
|---|---|---|
| Space | O(V + E) | O(V²) |
| Iterate neighbors of v | O(degree) | O(V) |
| "Is there an edge u → v?" | O(degree) | O(1) |
Visit by distance — start, then all 1-hop neighbors, then all 2-hop, then 3-hop. Implemented with a queue.
Key property: the first time you reach a node, you've reached it via the shortest path (in terms of number of edges). That makes BFS the go-to for shortest-path problems on unweighted graphs.
from collections import deque
def bfs(graph, start):
seen = {start}
q = deque([start])
while q:
v = q.popleft()
visit(v)
for u in graph[v]:
if u not in seen:
seen.add(u)
q.append(u)
# O(V + E) time and space
function bfs(graph, start) {
const seen = new Set([start]);
const q = [start]; let head = 0;
while (head < q.length) {
const v = q[head++];
visit(v);
for (const u of graph[v] || []) {
if (!seen.has(u)) { seen.add(u); q.push(u); }
}
}
}
// O(V + E) time and space
function bfs<T>(graph: Record<string, T[]>, start: T): void {
const seen = new Set<T>([start]);
const q: T[] = [start]; let head = 0;
while (head < q.length) {
const v = q[head++];
visit(v);
for (const u of (graph as any)[v as any] || []) {
if (!seen.has(u)) { seen.add(u); q.push(u); }
}
}
}
// O(V + E) time and space
Visit a path as deeply as possible before backtracking. Implemented with recursion (or an explicit stack).
Key property: gives you a topological structure of the search — which nodes were started, finished, and in what order. That's the foundation of cycle detection and topological sort.
def dfs(graph, start, seen=None):
if seen is None: seen = set()
if start in seen: return
seen.add(start)
visit(start)
for u in graph[start]:
dfs(graph, u, seen)
function dfs(graph, start, seen = new Set()) {
if (seen.has(start)) return;
seen.add(start);
visit(start);
for (const u of graph[start] || []) {
dfs(graph, u, seen);
}
}
function dfs<T>(graph: Record<string, T[]>, start: T, seen: Set<T> = new Set()): void {
if (seen.has(start)) return;
seen.add(start);
visit(start);
for (const u of (graph as any)[start as any] || []) {
dfs(graph, u, seen);
}
}
| Problem | Reach for | Why |
|---|---|---|
| "Shortest path on unweighted graph" | BFS | BFS visits in order of distance. |
| "All connected components / count islands" | BFS or DFS, whichever feels cleaner | Iterate every node, traverse from unvisited ones. |
| "Topological sort" / "course schedule" | DFS post-order, OR Kahn's BFS algorithm | Dependencies must come before dependents. |
| "Cycle in a directed graph" | DFS with recursion stack tracking | An edge to a node currently on the DFS stack = back edge = cycle. |
| "Word ladder" / shortest transformation | BFS on implicit graph | Build edges on the fly: two words are connected if they differ by one char. |
| "Shortest path on weighted graph" | Dijkstra (BFS + min-heap) | Greedy expansion of the closest unvisited node. |
"Number of islands" looks like a 2D-grid problem but is really a graph problem — each cell is a node, connected to its four neighbors. BFS or DFS from each unvisited land cell. You'll see this exact pattern half a dozen times during prep.