Data Structures Β· Visualization
Graph: Representations (Adjacency Matrix vs List)
Graph
A graph can be stored as an adjacency matrix (an nΓn grid marking which vertex pairs are connected) or an adjacency list (each vertex keeps a list of its neighbors). Time: Matrix: O(1) edge check, O(V) to list neighbors; List: O(V) edge check worst case, O(degree) to list neighbors. Space: Matrix: O(V^2); List: O(V + E).
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Representations (Adjacency Matrix vs List)
GraphA graph can be stored as an adjacency matrix (an nΓn grid marking which vertex pairs are connected) or an adjacency list (each vertex keeps a list of its neighbors). The choice trades memory for query speed depending on how dense the graph is.
How Representations (Adjacency Matrix vs List) Works
- Adjacency matrix: create an nΓn 2D array; set matrix[u][v] = 1 (or weight) whenever an edge exists between u and v.
- Adjacency matrix edge lookup 'does edge (u,v) exist?' is a single O(1) array access.
- Adjacency list: create an array of n lists; for each edge (u,v), append v to list[u] (and u to list[v] if undirected).
- Adjacency list traversal of a vertex's neighbors only visits its actual neighbors, not all n vertices.
Representations (Adjacency Matrix vs List) Worked Example
Input: Represent a 4-node graph with edges (0,1), (0,2), (1,2)
- Matrix (4x4): row0=[0,1,1,0], row1=[1,0,1,0], row2=[1,1,0,0], row3=[0,0,0,0]
- List: 0β[1,2], 1β[0,2], 2β[0,1], 3β[]
- Checking edge (0,3): matrix lookup is O(1) β 0 (no edge); list scan of list[0] is O(degree) β not found
Output: Same graph, two representations with different space/speed trade-offs
Press βΆ Run to watch it step by step.
vertices = ["A", "B", "C", "D"]
edges = [("A", "B", 4), ("A", "C", 2)]
adj_list = {v: [] for v in vertices}
for a, b, w in edges: # adjacency list
adj_list[a].append((b, w))
adj_matrix = [[0] * len(vertices) for _ in vertices]
for a, b, w in edges: # adjacency matrix
adj_matrix[vertices.index(a)][vertices.index(b)] = w
print(adj_list)
print(adj_matrix) # O(V^2) space, O(1) edge check
# example: reprBehind the Scenes Execution
Press βΆ Run in the visualizer β the call stack, registers and memory will replay here in sync with the code, line by line.
Representations (Adjacency Matrix vs List) Time & Space Complexity
When to Use Representations (Adjacency Matrix vs List)
- Dense graphs (many edges) favor matrices
- Sparse graphs (few edges) favor lists β most real-world graphs
- Algorithm choice depends on representation (Floyd-Warshall wants a matrix, BFS/DFS prefer a list)
Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action β visualize the algorithms that operate on these structures, or take a guided course.