Discover how choosing the right way to store connections can save you time and memory!
Adjacency List vs Matrix When to Choose Which in DSA Python - Why the Distinction Matters
Imagine you want to keep track of friendships in a large school. You try to write down every possible pair of students and whether they are friends or not on a huge grid.
This grid grows very big and becomes hard to manage as the school size increases.
Using a big grid (matrix) wastes a lot of space when most students have only a few friends.
It also takes longer to find who is friends with whom because you check many empty spots.
Writing down every possible pair is slow and confusing.
Using an adjacency list, you only write down the friends each student actually has.
This saves space and makes it faster to find friends because you look only where there is a connection.
You avoid wasting time and memory on empty pairs.
graph = [[0]*1000 for _ in range(1000)] # 1000 students, mostly zeros # To check if student 5 is friends with 10 if graph[5][10] == 1: print('Friends')
graph = {i: [] for i in range(1000)} # 1000 students
# Add friend
graph[5].append(10)
# Check friend
if 10 in graph[5]:
print('Friends')You can efficiently manage and explore large networks with many nodes but few connections.
Social media platforms use adjacency lists to store user connections because most users have a limited number of friends compared to the total user base.
Adjacency matrix uses more space but is simple for dense graphs.
Adjacency list saves space and is faster for sparse graphs.
Choosing the right method depends on how many connections exist.
Practice
Solution
Step 1: Understand graph density
A graph with very few edges compared to vertices is called a sparse graph.Step 2: Choose efficient representation for sparse graphs
Adjacency lists store only existing edges, saving space for sparse graphs, unlike adjacency matrices which use space for all possible edges.Final Answer:
Adjacency List -> Option AQuick Check:
Sparse graph = Adjacency List [OK]
- Choosing adjacency matrix for sparse graphs wastes space
- Confusing edge list with adjacency matrix
- Assuming adjacency matrix is always better
Solution
Step 1: Understand matrix initialization
Using list comprehension with nested loops creates independent inner lists.Step 2: Avoid shallow copies
matrix = [[0]*4]*4 creates shallow copies causing all rows to reference the same list, leading to bugs.Final Answer:
matrix = [[0 for _ in range(4)] for _ in range(4)] -> Option AQuick Check:
Independent rows = matrix = [[0 for _ in range(4)] for _ in range(4)] [OK]
- Using [[0]*4]*4 causes all rows to be the same object
- Initializing with single list for matrix
- Using None instead of 0 for adjacency matrix
graph = {0: [1, 2], 1: [2], 2: []}
print(graph[1])What is the output?
Solution
Step 1: Understand adjacency list structure
Key 1 maps to list [2], meaning vertex 1 connects to vertex 2.Step 2: Print value for key 1
graph[1] returns [2], so print outputs [2].Final Answer:
[2] -> Option CQuick Check:
graph[1] = [2] [OK]
- Confusing keys and values in dictionary
- Expecting all vertices in output
- Assuming KeyError for existing key
matrix = [[0]*3]*3 matrix[0][1] = 1 print(matrix)
What is the output and what is the bug?
Solution
Step 1: Understand matrix initialization
Using [[0]*3]*3 creates 3 references to the same inner list.Step 2: Modify one element affects all rows
Setting matrix[0][1] = 1 changes the second element in all rows because they share the same list.Final Answer:
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]; Rows are shallow copies -> Option DQuick Check:
Shallow copy rows cause all rows to change [OK]
- Assuming only first row changes
- Ignoring shallow copy behavior
- Confusing IndexError with shallow copy bug
Solution
Step 1: Analyze graph density and operations
Graph has 1000 vertices and 10,000 edges, which is moderately sparse but not very sparse.Step 2: Consider operation speed for edge checks
Adjacency matrix allows checking edge existence in constant time O(1), while adjacency list requires searching neighbors.Step 3: Balance memory and speed
Though adjacency matrix uses more memory, the speed benefit for frequent edge checks outweighs memory cost here.Final Answer:
Adjacency Matrix, because it allows O(1) edge existence checks -> Option BQuick Check:
Frequent edge check = Adjacency Matrix [OK]
- Choosing adjacency list only for memory without considering speed
- Ignoring operation frequency in choice
- Confusing edge list with adjacency matrix for fast checks
Ready to prove it?
Pass the test and this pattern moves unknown
