Module 5 · Lesson 1 · ~25 min

Graphs — representations and traversals

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.

The metaphor: a city's roads, or your friend network

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.

The metaphor

Trees are family trees: a parent has children, no cycles. Graphs are friend networks: cycles everywhere, multiple paths between two people, sometimes islands of disconnected groups.

Two ways to represent a graph

Adjacency list (the one you use)

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([...]);

Adjacency matrix

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.

OperationAdjacency listAdjacency matrix
SpaceO(V + E)O(V²)
Iterate neighbors of vO(degree)O(V)
"Is there an edge u → v?"O(degree)O(1)

BFS vs. DFS — the two traversals that solve everything

BFS — breadth-first search

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

DFS — depth-first search

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);
  }
}

The pattern recognizer

ProblemReach forWhy
"Shortest path on unweighted graph"BFSBFS visits in order of distance.
"All connected components / count islands"BFS or DFS, whichever feels cleanerIterate every node, traverse from unvisited ones.
"Topological sort" / "course schedule"DFS post-order, OR Kahn's BFS algorithmDependencies must come before dependents.
"Cycle in a directed graph"DFS with recursion stack trackingAn edge to a node currently on the DFS stack = back edge = cycle.
"Word ladder" / shortest transformationBFS on implicit graphBuild 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.
Interview reality

"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.

Try it: number of islands