Challenge - 5 Problems
Adjacency Matrix Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of adjacency matrix after adding edges
What is the printed adjacency matrix after adding edges between nodes 0-1, 1-2, and 2-0 in an undirected graph with 3 nodes?
DSA Python
n = 3 adj_matrix = [[0]*n for _ in range(n)] # Add edges adj_matrix[0][1] = 1 adj_matrix[1][0] = 1 adj_matrix[1][2] = 1 adj_matrix[2][1] = 1 adj_matrix[2][0] = 1 adj_matrix[0][2] = 1 for row in adj_matrix: print(row)
Attempts:
2 left
💡 Hint
Remember that for an undirected graph, edges are symmetric in the adjacency matrix.
✗ Incorrect
Since the graph is undirected, each edge is represented twice symmetrically in the matrix. Adding edges 0-1, 1-2, and 2-0 sets those pairs to 1 in both directions.
❓ Predict Output
intermediateOutput of adjacency matrix for directed graph
What is the printed adjacency matrix after adding directed edges from node 0 to 1, and from node 1 to 2 in a graph with 3 nodes?
DSA Python
n = 3 adj_matrix = [[0]*n for _ in range(n)] # Add directed edges adj_matrix[0][1] = 1 adj_matrix[1][2] = 1 for row in adj_matrix: print(row)
Attempts:
2 left
💡 Hint
Directed edges only set one direction in the matrix.
✗ Incorrect
Directed edges set the matrix entry from source to destination to 1 only. So 0->1 and 1->2 are set, others remain 0.
🧠 Conceptual
advancedMemory usage of adjacency matrix vs adjacency list
Which statement correctly compares memory usage between adjacency matrix and adjacency list for a graph with n nodes and e edges?
Attempts:
2 left
💡 Hint
Think about how adjacency matrix stores all possible edges.
✗ Incorrect
Adjacency matrix stores a fixed n x n matrix, so memory is O(n^2). Adjacency list stores only existing edges, so memory is O(n + e).
🔧 Debug
advancedIdentify the error in adjacency matrix edge addition
What error will this code produce when adding an edge in an undirected graph with 3 nodes?
Code:
n = 3
adj_matrix = [[0]*n for _ in range(n)]
# Add edge between 0 and 3
adj_matrix[0][3] = 1
adj_matrix[3][0] = 1
Attempts:
2 left
💡 Hint
Check the valid indices for a list of size 3.
✗ Incorrect
Index 3 is out of range for a list of size 3 (indices 0,1,2). Accessing adj_matrix[0][3] causes IndexError.
🚀 Application
expertNumber of edges in an undirected graph from adjacency matrix
Given the adjacency matrix below for an undirected graph, how many edges does the graph have?
adj_matrix = [
[0, 1, 0, 1],
[1, 0, 1, 0],
[0, 1, 0, 1],
[1, 0, 1, 0]
]
Attempts:
2 left
💡 Hint
Count the number of 1s above the main diagonal.
✗ Incorrect
In an undirected graph adjacency matrix, edges are counted by summing 1s above the diagonal. Here, edges are (0-1), (0-3), (1-2), (2-3) totaling 4 edges.
