Adjacency Matrix Representation in DSA Python - Time & Space Complexity
We want to understand how the time to check or update connections in a graph grows as the graph gets bigger.
How does the number of nodes affect the work needed with an adjacency matrix?
Analyze the time complexity of the following code snippet.
# Create adjacency matrix for n nodes
n = 4
adj_matrix = [[0] * n for _ in range(n)]
# Add edge between node 1 and 3
adj_matrix[1][3] = 1
# Check if edge exists between node 0 and 2
exists = adj_matrix[0][2] == 1
This code creates a matrix to store connections, adds one connection, and checks if another connection exists.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating the matrix uses a loop to fill rows and columns.
- How many times: The matrix creation loops run n times for rows and n times for columns, so n × n = n² times.
When the number of nodes doubles, the matrix size grows by four times because it stores connections for every pair of nodes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 100 (10×10) |
| 100 | 10,000 (100×100) |
| 1000 | 1,000,000 (1000×1000) |
Pattern observation: The work grows with the square of the number of nodes.
Time Complexity: O(n²)
This means the time to create or check the matrix grows quickly as the number of nodes increases, specifically by the square of the nodes.
[X] Wrong: "Checking if an edge exists is slow because it needs to look through many connections."
[OK] Correct: Checking one connection in an adjacency matrix is actually very fast, just one direct lookup, which is O(1).
Understanding adjacency matrix time complexity helps you explain trade-offs in graph storage and access, a common topic in interviews.
"What if we used an adjacency list instead of a matrix? How would the time complexity for checking edges 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 yes, 0 for no).Final Answer:
A 2D array showing connections between nodes -> Option AQuick Check:
Adjacency matrix = 2D array of connections [OK]
- Confusing adjacency matrix with adjacency list
- Thinking it stores node values instead of connections
- Assuming it is a list or sequence
Solution
Step 1: Understand correct 2D list initialization
Using list comprehension creates independent inner lists for each row.Step 2: Analyze each option
matrix = [[0]*3]*3 creates shallow copies causing all rows to reference the same list, which is incorrect. matrix = [[0 for _ in range(3)] for _ in range(3)] correctly creates separate lists. Options C and D create 1D lists, not 2D.Final Answer:
matrix = [[0 for _ in range(3)] for _ in range(3)] -> Option DQuick Check:
Use list comprehension for independent rows [OK]
- Using [[0]*3]*3 causes all rows to be same object
- Creating 1D list instead of 2D
- Forgetting to nest loops for rows and columns
graph = [[0,1,0],[1,0,1],[0,1,0]]
for i in range(3):
for j in range(3):
if graph[i][j] == 1:
print(f"Edge between {i} and {j}")Solution
Step 1: Analyze the adjacency matrix
Matrix shows edges: (0,1), (1,0), (1,2), (2,1) as 1s.Step 2: Trace nested loops and print statements
Loops check each cell; when value is 1, print edge between i and j.Final Answer:
Edge between 0 and 1 Edge between 1 and 0 Edge between 1 and 2 Edge between 2 and 1 -> Option BQuick Check:
Print edges where matrix cell is 1 [OK]
- Ignoring symmetric edges in undirected graph
- Printing only one direction of edges
- Confusing indices i and j
n = 4 matrix = [[0]*n]*n matrix[0][1] = 1 print(matrix)
Solution
Step 1: Understand matrix initialization
Using [[0]*n]*n creates shallow copies; all rows point to the same list.Step 2: Effect of modifying one element
Changing matrix[0][1] changes that column in all rows because they share the same list.Final Answer:
The matrix initialization causes all rows to be the same list -> Option AQuick Check:
Use nested list comprehension to avoid shared rows [OK]
- Assuming rows are independent lists
- Ignoring shared reference problem
- Thinking print syntax is wrong
Solution
Step 1: Map edges to matrix positions
Edge 0->1 means matrix[0][1] = 1, 1->2 means matrix[1][2] = 1, 2->0 means matrix[2][0] = 1.Step 2: Check each option against edges
[[0,1,0],[0,0,1],[1,0,0]] matches these exactly; others have extra or missing edges.Final Answer:
[[0,1,0],[0,0,1],[1,0,0]] -> Option CQuick Check:
Edges map to 1s in correct matrix cells [OK]
- Confusing directed and undirected edges
- Setting symmetric edges for directed graph
- Misplacing 1s in wrong matrix cells
Ready to prove it?
Pass the test and this pattern moves unknown
