Skip to main content

DSAPath12 mincore

Adjacency List vs Adjacency Matrix

Adjacency lists are compact for sparse graphs; adjacency matrices give constant-time edge checks but cost quadratic space.

DifficultyCore
TierTier 1
ModuleComparisons
LanguagesPython

Why This Matters

Graph algorithms depend on representation. The same graph can be cheap or expensive to traverse depending on how neighbors are stored.

Decision Rule

Use an adjacency list for sparse graphs and neighbor traversal. Use an adjacency matrix when the graph is dense or the dominant operation is checking whether a specific edge exists.

Comparison Table

FeatureAdjacency listAdjacency matrix
SpaceO(V + E)O(V^2)
Check edge u -> vO(deg(u)) or better with setsO(1)
Iterate neighborsO(deg(u))O(V)
Sparse graph fitexcellentwasteful
Dense graph fitfineoften acceptable
Common algorithmsBFS, DFS, DijkstraFloyd-Warshall, dense graph operations

Worked Example

A graph with one million vertices and two million edges is sparse. An adjacency matrix would need space for 10^12 possible entries, which is not practical for ordinary storage.

An adjacency list stores only existing edges, so traversal algorithms process real neighbors rather than scanning mostly empty rows.

Common Mistakes

MistakeCorrection
Using a matrix for a huge sparse graph.Use an adjacency list.
Assuming list edge checks are always constant time.A plain list may scan neighbors; a set-backed adjacency can speed membership.
Ignoring algorithm expectations.Some algorithms, such as Floyd-Warshall, are naturally matrix-shaped.

Diagnostic Questions

QuestionAnswer signal
Which representation uses O(V^2) space?Adjacency matrix.
Which is better for BFS on a sparse graph?Adjacency list.
Which gives constant-time edge existence checks?Adjacency matrix, or set-backed adjacency lists with different tradeoffs.

Exercises

  • Beginner: Convert a three-edge graph into an adjacency list.
  • Beginner: Convert the same graph into an adjacency matrix.
  • Beginner: Identify whether a graph with E near V is sparse or dense.
  • Intermediate: Implement BFS with an adjacency list.
  • Intermediate: Compare memory use for V = 10,000 with sparse edges.
  • Challenge: Explain why Floyd-Warshall uses a distance matrix.

References