When working with graphs in computer science, one of the first decisions you need to make is how to store them efficiently. The two most common representations are the Adjacency Matrix and the Adjacency List. Each has its advantages and trade-offs, making them suitable for different scenarios.
In this article, we’ll compare these two data structures in terms of memory usage, performance, and real-world applications to help you decide which one to use for your projects.
An adjacency matrix is a 2D array where each cell [i][j]
indicates whether there is an edge between vertex i
and vertex j
.
For a graph with n
vertices, we use an n × n
matrix:
matrix[i][j] = 1
(or weight w
) if there is an edge from i
to j
matrix[i][j] = 0
if there is no edgeFor a graph with 4 vertices:
0 1 2 3
0 [0, 1, 0, 1]
1 [1, 0, 1, 1]
2 [0, 1, 0, 0]
3 [1, 1, 0, 0]
n × n
values, this is inefficient for large, sparse graphs.✅ Fast lookups – Checking if an edge exists is constant time O(1).
✅ Simple implementation – Easy to code and understand.
❌ Memory-intensive – Always requires O(n²)
space, even for sparse graphs.
❌ Slow iteration – Iterating over neighbors takes O(n)
time.
An adjacency list represents a graph as an array of linked lists or vectors. Each vertex stores a list of adjacent nodes.
For n
vertices, we store an array where each index corresponds to a list of neighbors.
For the same graph as above:
0 → {1, 3}
1 → {0, 2, 3}
2 → {1}
3 → {0, 1}
m
is the number of edges – more efficient for sparse graphs.✅ Efficient for sparse graphs – Uses much less memory than an adjacency matrix.
✅ Faster iteration – Traversing neighbors is efficient for small-degree nodes.
❌ Slower edge lookup – Checking if an edge exists can take O(n) in the worst case.
Criteria | Adjacency Matrix | Adjacency List |
---|---|---|
Memory Usage | O(n²) (bad for sparse graphs) | O(n + m) (good for sparse graphs) |
Edge Lookup Time | O(1) (fast) | O(degree of node) (slower for dense graphs) |
Adding an Edge | O(1) (fast) | O(1) (fast) |
Removing an Edge | O(1) (fast) | O(degree of node) (slower for large degrees) |
Iterating Neighbors | O(n) (slow) | O(degree of node) (fast) |
Best for | Dense graphs | Sparse graphs |
m ≈ n²
).m << n²
).Choosing between an Adjacency Matrix and an Adjacency List depends on your graph’s characteristics and the operations you need to perform.