Stage 1 · Code
Graphs & Backtracking
Graph Representations & Traversals
Master adjacency lists, DFS, and BFS — the three tools that unlock 80% of graph interview problems.
Adjacency List vs Adjacency Matrix
A graph is a collection of nodes (vertices) and edges connecting them. Two common ways to store a graph in code:
| Property | Adjacency List | Adjacency Matrix |
|---|---|---|
| Storage | O(V + E) | O(V²) |
| Edge lookup | O(degree) ≈ O(V) worst | O(1) |
| Iterate neighbors | O(degree) ≈ fast | O(V) — must scan full row |
| Weighted edges | Store pair (neighbor, weight) | Store weight in cell |
| Common in interviews | Almost always | Rare — dense graphs only |
For nearly every LeetCode graph problem, an adjacency list is the right choice. It is sparse-friendly and iterating neighbors is fast.
Depth-First Search (DFS)
DFS explores as far as possible along each branch before backtracking. Implemented recursively (implicit call stack) or iteratively (explicit stack). Critical for connectivity, cycle detection, and topological ordering.
For grid-based problems (Number of Islands), DFS on a 2D matrix is the go-to pattern. Each cell is a node; directional neighbors are edges.
Breadth-First Search (BFS)
BFS explores nodes level by level using a queue. It guarantees the shortest path in unweighted graphs and is the right tool for spreading processes (rotten oranges, infection, word ladder).
DFS vs BFS
| Criterion | DFS | BFS |
|---|---|---|
| Data structure | Stack (recursive or explicit) | Queue |
| Shortest path in unweighted graph | No — finds any path | Yes — guaranteed shortest |
| Space complexity | O(h) where h = depth | O(w) where w = max width (often larger) |
| Cycle detection | Yes — back edge in recursion | Less natural |
| Topological sort | Yes — post-order DFS | Yes — Kahn's algorithm |
| Connected components | Natural fit | Also works |
Need shortest path in an unweighted graph? Use BFS. Need to exhaust all possibilities or detect cycles? Use DFS. Both can count connected components and detect bipartiteness, but BFS feels more natural for 'levels' while DFS feels natural for 'paths'.
When to Use
- Adjacency list for almost all problems — sparse graphs with up to 10⁵ nodes.
- DFS when you need to explore all paths, detect cycles, or perform flood fill.
- BFS when the graph is unweighted and you need the shortest number of edges.
- Grid as graph when the input is a 2D matrix (
grid[r][c]= node, 4-dir moves = edges). - Clone graph / deep copy: DFS with a cache of cloned nodes (node → clone).
Problems
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.