Adjacency Matrix Representation in DSA Rust - Time & Space Complexity
We want to understand how the time to work with an adjacency matrix changes as the graph grows.
Specifically, how long it takes to check connections or build the matrix as the number of nodes increases.
Analyze the time complexity of the following code snippet.
fn create_adjacency_matrix(n: usize, edges: &[(usize, usize)]) -> Vec> {
let mut matrix = vec![vec![0; n]; n];
for &(u, v) in edges {
matrix[u][v] = 1;
matrix[v][u] = 1; // for undirected graph
}
matrix
}
This code builds an adjacency matrix for an undirected graph with n nodes and given edges.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over all edges to update the matrix.
- How many times: Once for each edge in the list.
As the number of nodes and edges grow, the time to build the matrix grows mainly with the number of edges.
| Input Size (n) | Approx. Operations (edges) |
|---|---|
| 10 nodes, 15 edges | 15 updates |
| 100 nodes, 500 edges | 500 updates |
| 1000 nodes, 2000 edges | 2000 updates |
Pattern observation: The time grows roughly with the number of edges, not just nodes.
Time Complexity: O(n^2)
This means the time to build or check the matrix grows with the square of the number of nodes, because the matrix size is n by n.
[X] Wrong: "Building the adjacency matrix only takes time proportional to the number of edges."
[OK] Correct: While updating edges is proportional to edges, the matrix itself is size n by n, so operations like checking all connections or initializing the matrix take time proportional to n squared.
Understanding adjacency matrix time complexity helps you choose the right graph representation and explain trade-offs clearly in interviews.
"What if we used an adjacency list instead of a matrix? How would the time complexity change?"
Practice
Solution
Step 1: Understand adjacency matrix concept
An adjacency matrix is a 2D array where rows and columns represent nodes.Step 2: Identify what the matrix stores
Each cell shows if an edge exists between two nodes (1 for edge, 0 for no edge).Final Answer:
A 2D array showing edges between nodes -> Option BQuick Check:
Adjacency matrix = 2D edge array [OK]
- Confusing adjacency matrix with adjacency list
- Thinking it stores node values instead of edges
- Mixing it with traversal order
Solution
Step 1: Understand Rust 2D vector initialization
Rust uses Vec for dynamic 2D arrays; vec![vec![0; 3]; 3] creates 3 rows of 3 zeros.Step 2: Check each option for correctness
A: [[0; 3]; 3] creates fixed-size array [[i32;3]; 3], not Vec. B: [0; 3][0; 3] is invalid syntax. D: [[0, 0, 0], [0, 0, 0]] has only 2 rows.Final Answer:
let matrix = vec![vec![0; 3]; 3]; -> Option AQuick Check:
vec![vec![0; 3]; 3] creates 3x3 zero matrix [OK]
- Using invalid syntax for 2D arrays
- Confusing fixed arrays with vectors
- Incorrect row or column count
let mut matrix = vec![vec![0; 3]; 3];
matrix[0][1] = 1;
matrix[1][2] = 1;
for row in &matrix {
println!("{:?}", row);
}Solution
Step 1: Initialize 3x3 zero matrix
matrix starts as [[0,0,0],[0,0,0],[0,0,0]].Step 2: Update edges as per code
matrix[0][1] = 1 sets edge from node 0 to 1; matrix[1][2] = 1 sets edge from node 1 to 2.Step 3: Print matrix rows
Rows print as [0,1,0], [0,0,1], [0,0,0].Final Answer:
[0, 1, 0]\n[0, 0, 1]\n[0, 0, 0] -> Option CQuick Check:
Edges at (0,1) and (1,2) = 1 [OK]
- Mixing row and column indices
- Assuming symmetric edges in directed graph
- Printing matrix incorrectly
let mut matrix = vec![vec![0; 3]; 3]; matrix[3][0] = 1;
Solution
Step 1: Check vector size and indices
matrix is 3x3 with valid indices 0,1,2 for rows and columns.Step 2: Analyze matrix[3][0] access
Index 3 is out of bounds for rows (max index 2), causing runtime panic.Final Answer:
Index out of bounds error -> Option AQuick Check:
Accessing index 3 in size 3 vector causes error [OK]
- Using invalid indices beyond matrix size
- Confusing compile-time and runtime errors
- Ignoring Rust's panic on out-of-bounds
Solution
Step 1: Understand node indexing and edges
Nodes are 0 to 3. Edges: 0->1, 0->2, 3->0.Step 2: Map edges to adjacency matrix
Row 0 has 1s at columns 1 and 2. Row 3 has 1 at column 0. Others are 0.Step 3: Verify options
[[0, 1, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0]] matches this exactly. Others have wrong edges or self loops.Final Answer:
[[0, 1, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0]] -> Option DQuick Check:
Edges 0->1,0->2 and 3->0 set correctly [OK]
- Mixing up row and column meaning
- Adding edges not specified
- Confusing directed with undirected edges
Ready to prove it?
Pass the test and this pattern moves unknown
