← Graph Exploration

Micro-Drill #223 — Graph representations: adj list vs matrix vs edge list

Graph Exploration Target: 15s

Adjacency list is the default for interviews. Use matrix for dense graphs or O(1) edge lookup. Edge list for MST.

GRAPH REPRESENTATIONS
─────────────────────
ADJACENCY LIST: graph[u] = [v1, v2, ...]
  + Space: O(V + E) — sparse-friendly
  + Iterate neighbors: O(degree)
  + Add edge: O(1)
  - Check edge exists: O(degree)
  Best for: most problems, sparse graphs

ADJACENCY MATRIX: graph[u][v] = weight
  + Check edge exists: O(1)
  + Dense graph efficient
  - Space: O(V²) — wasteful if sparse
  - Iterate neighbors: O(V)
  Best for: dense graphs, Floyd-Warshall

EDGE LIST: [(u, v, weight), ...]
  + Simple, compact
  + Natural for Kruskal's (sort by weight)
  - Check edge/neighbors: O(E)
  Best for: Kruskal's MST, reading input

PYTHON PATTERNS:
  Adj list: graph = defaultdict(list)
            graph[u].append(v)
  Matrix:   graph = [[0]*n for _ in range(n)]
  Weighted: graph[u].append((v, weight))

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #222 Micro #224 →