Graphs
Representation
Section titled “Representation”// Adjacency list from an edge list (most common)List<List<Integer>> graph = new ArrayList<>();for (int i = 0; i < n; i++) graph.add(new ArrayList<>());for (int[] e : edges) { graph.get(e[0]).add(e[1]); graph.get(e[1]).add(e[0]); // omit for directed graphs}
// Grid: neighbors via direction arraysint[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};for (int[] d : dirs) { int nr = r + d[0], nc = c + d[1]; if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue; // ...}| Representation | Space | Check edge (u, v) | Iterate neighbors |
|---|---|---|---|
| Adjacency list | O(V + E) | O(deg) | O(deg) |
| Adjacency matrix | O(V²) | O(1) | O(V) |
Use an adjacency list unless the graph is dense or tiny.
Templates
Section titled “Templates”// BFS: shortest path in an unweighted graphboolean[] visited = new boolean[n];Queue<Integer> q = new ArrayDeque<>();q.offer(start);visited[start] = true; // mark when ENQUEUING, not when pollingint steps = 0;while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { int u = q.poll(); // if (u == target) return steps; for (int v : graph.get(u)) { if (!visited[v]) { visited[v] = true; q.offer(v); } } } steps++;}
// DFS: recursivevoid dfs(int u, List<List<Integer>> graph, boolean[] visited) { visited[u] = true; for (int v : graph.get(u)) { if (!visited[v]) dfs(v, graph, visited); }}Say this: “BFS explores in layers, so the first time I reach a node is via the shortest path when edges are unweighted. DFS is simpler for ‘explore everything connected’.”
Problems
Section titled “Problems”Problem: Number of Islands (Medium) — LC 200
Approach (say out loud): “Scan every cell. When I hit unvisited land, that’s a new island, so I count it and flood-fill (DFS) to sink all connected land. I mark visited by changing ‘1’ to ‘0’ in place, after asking if mutating the input is okay.”
Java:
class Solution { public int numIslands(char[][] grid) { int count = 0; for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[0].length; c++) { if (grid[r][c] == '1') { count++; sink(grid, r, c); } } } return count; }
private void sink(char[][] grid, int r, int c) { if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] != '1') return; grid[r][c] = '0'; sink(grid, r + 1, c); sink(grid, r - 1, c); sink(grid, r, c + 1); sink(grid, r, c - 1); }}Complexity: O(m·n) time, O(m·n) space worst case (recursion depth)
Edge cases: all water → 0, all land → 1. Diagonal cells don’t count as connected. For very large grids, use BFS to avoid a stack overflow.
Problem: Clone Graph (Medium) — LC 133
Approach (say out loud): “DFS with a map from original node to its clone. The map also works as the visited set, which handles cycles. For each node, I create the clone first, put it in the map, then clone its neighbors.”
Java:
class Solution { private final Map<Node, Node> clones = new HashMap<>();
public Node cloneGraph(Node node) { if (node == null) return null; if (clones.containsKey(node)) return clones.get(node); Node copy = new Node(node.val, new ArrayList<>()); clones.put(node, copy); // put BEFORE recursing (handles cycles) for (Node nb : node.neighbors) { copy.neighbors.add(cloneGraph(nb)); } return copy; }}Complexity: O(V + E) time, O(V) space
Edge cases: a null node, a single node with no neighbors, cycles.
Problem: Course Schedule, Topological Sort (Medium) — LC 207 / 210
Approach (say out loud): “Courses are nodes, and prerequisites are directed edges pre → course. I can finish everything only if there’s no cycle. Kahn’s algorithm: count in-degrees, start a queue with all zero in-degree nodes, and repeatedly remove a node and decrement its neighbors. If I process all n nodes, there’s no cycle. The processing order is the topological order (LC 210).”
Java:
class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { List<List<Integer>> graph = new ArrayList<>(); for (int i = 0; i < numCourses; i++) graph.add(new ArrayList<>()); int[] indegree = new int[numCourses]; for (int[] p : prerequisites) { graph.get(p[1]).add(p[0]); // p[1] must come before p[0] indegree[p[0]]++; }
Queue<Integer> q = new ArrayDeque<>(); for (int i = 0; i < numCourses; i++) if (indegree[i] == 0) q.offer(i);
int[] order = new int[numCourses]; int idx = 0; while (!q.isEmpty()) { int u = q.poll(); order[idx++] = u; for (int v : graph.get(u)) { if (--indegree[v] == 0) q.offer(v); } } return idx == numCourses ? order : new int[0]; }
// LC 207 is the same thing returning a boolean public boolean canFinish(int numCourses, int[][] prerequisites) { return findOrder(numCourses, prerequisites).length == numCourses; }}Complexity: O(V + E) time, O(V + E) space
Edge cases: no prerequisites (any order works), a self-loop [0,0] (cycle), disconnected components.
Problem: Rotting Oranges, Multi-source BFS (Medium) — LC 994
Approach (say out loud): “Every rotten orange spreads at the same time, so I put ALL of them in the queue at minute 0. That’s multi-source BFS. Each BFS layer is one minute. I count fresh oranges, and if any remain at the end, return -1.”
Java:
class Solution { public int orangesRotting(int[][] grid) { int rows = grid.length, cols = grid[0].length, fresh = 0; Queue<int[]> q = new ArrayDeque<>(); for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (grid[r][c] == 2) q.offer(new int[]{r, c}); else if (grid[r][c] == 1) fresh++; } }
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int minutes = 0; while (!q.isEmpty() && fresh > 0) { int size = q.size(); for (int i = 0; i < size; i++) { int[] cell = q.poll(); for (int[] d : dirs) { int nr = cell[0] + d[0], nc = cell[1] + d[1]; if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] != 1) continue; grid[nr][nc] = 2; fresh--; q.offer(new int[]{nr, nc}); } } minutes++; } return fresh == 0 ? minutes : -1; }}Complexity: O(m·n) time, O(m·n) space
Edge cases: no fresh oranges → 0 (this is why the loop also checks fresh > 0), a fresh orange that no rotten orange can reach → -1.
Problem: Network Delay Time, Dijkstra (Medium) — LC 743
Approach (say out loud): “Weighted shortest path from one source with non-negative weights, so Dijkstra. A min-heap of (distance, node). I pop the closest node. If I’ve already found a shorter distance for it, I skip it. Otherwise I relax its edges. The answer is the max distance, or -1 if some node is unreachable.”
Java:
class Solution { public int networkDelayTime(int[][] times, int n, int k) { List<List<int[]>> graph = new ArrayList<>(); for (int i = 0; i <= n; i++) graph.add(new ArrayList<>()); for (int[] t : times) graph.get(t[0]).add(new int[]{t[1], t[2]});
int[] dist = new int[n + 1]; Arrays.fill(dist, Integer.MAX_VALUE); dist[k] = 0; PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])); pq.offer(new int[]{0, k});
while (!pq.isEmpty()) { int[] top = pq.poll(); int d = top[0], u = top[1]; if (d > dist[u]) continue; // stale entry for (int[] edge : graph.get(u)) { int v = edge[0], w = edge[1]; if (d + w < dist[v]) { dist[v] = d + w; pq.offer(new int[]{dist[v], v}); } } }
int max = 0; for (int i = 1; i <= n; i++) { if (dist[i] == Integer.MAX_VALUE) return -1; max = Math.max(max, dist[i]); } return max; }}Complexity: O(E log V) time, O(V + E) space
Edge cases: an unreachable node → -1, nodes are 1-indexed. Dijkstra fails with negative weights (then use Bellman-Ford). Say that if asked.
Problem: Number of Connected Components / Union-Find (Medium) — LC 323 / 547
Approach (say out loud): “Union-Find (Disjoint Set Union). Each node starts as its own parent. find follows parents to the root, with path compression. union links two roots, using union by rank. Each successful union merges two components, so components = n minus the number of successful unions.”
Java:
class UnionFind { private final int[] parent, rank; int components;
UnionFind(int n) { parent = new int[n]; rank = new int[n]; components = n; for (int i = 0; i < n; i++) parent[i] = i; }
int find(int x) { if (parent[x] != x) parent[x] = find(parent[x]); // path compression return parent[x]; }
boolean union(int a, int b) { int ra = find(a), rb = find(b); if (ra == rb) return false; // already connected, so this edge forms a cycle if (rank[ra] < rank[rb]) { int t = ra; ra = rb; rb = t; } parent[rb] = ra; if (rank[ra] == rank[rb]) rank[ra]++; components--; return true; }}
class Solution { public int countComponents(int n, int[][] edges) { UnionFind uf = new UnionFind(n); for (int[] e : edges) uf.union(e[0], e[1]); return uf.components; }}Complexity: close to O(1) per operation (inverse Ackermann α(n)), so O(n + E) overall. O(n) space.
Edge cases: no edges → n components. union returning false gives you Redundant Connection (LC 684) for free.