Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Adjacency Matrix itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)An adjacency matrix buys constant-time lookup of one ordered vertex pair at quadratic storage cost. Independent rows and explicit cell meaning preserve edge state; common-neighbor queries still scan complete rows, so they have a different cost.
1 practice exercise4 interview problems
Recognize it when The graph is dense, vertex count is small, or arbitrary pair lookup dominates.
Checking your account…
An adjacency matrix assigns one cell to every ordered vertex pair. matrix[u][v] states whether or
with what weight edge u → v exists, even when most cells are empty.
The matrix always uses O(V squared) space. Directed graphs need not be symmetric. In a simple
undirected graph, matrix[u][v] == matrix[v][u]; diagonal cells represent self-loops rather than
ordinary vertices.
Allocate rows independently, then write both directions for each undirected edge. Duplicate edges overwrite the same cells harmlessly when the matrix stores booleans.
def build_adjacency_matrix(node_count, edges):
matrix = [[0 for _ in range(node_count)] for _ in range(node_count)]
for left, right in edges:
matrix[left][right] = 1
matrix[right][left] = 1
return matrixImplement build_adjacency_matrix(node_count, edges). Return an independent-row 0/1 matrix for an undirected graph, including self-loops. node_count is a nonnegative integer; every edge endpoint is in 0 <= endpoint < node_count.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def build_adjacency_matrix(node_count, edges):
matrix = [[0 for _ in range(node_count)] for _ in range(node_count)]
for left, right in edges:
matrix[left][right] = 1
matrix[right][left] = 1
return matrixOne edge query is O(1). Enumerating all neighbors still scans a complete row in O(V), and counting common neighbors compares two rows in O(V). This tradeoff favors dense graphs or query-heavy tasks.
def edge_query_summary(matrix, queries):
result = []
for left, right in queries:
common = sum(a and b for a, b in zip(matrix[left], matrix[right]))
result.append([bool(matrix[left][right]), common])
return resultImplement edge_query_summary(matrix, queries). For each (u, v), return [has_edge, common_neighbor_count]. matrix is square with only 0/1 cells; all query endpoints are valid vertex indices.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def edge_query_summary(matrix, queries):
result = []
for left, right in queries:
common = sum(a and b for a, b in zip(matrix[left], matrix[right]))
result.append([bool(matrix[left][right]), common])
return resultUse the actual row-query Lab on a three-vertex path. Vertices 0 and 2 have no direct edge but share neighbor 1. Querying vertex 1 with itself counts its two neighbors while its absent self-loop remains False.
print(edge_query_summary([[0, 1, 0], [1, 0, 1], [0, 1, 0]], [(0, 2), (1, 1)])) followed by print(edge_query_summary([], []))
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | for left, right in queries: |
left = 0; right = 2; rows = [0, 1, 0] and [0, 1, 0] |
Matching columns describe the same possible neighbor vertices. |
| 2 | common = sum(a and b for a, b in zip(matrix[left], matrix[right])) |
contributions = 0, 1, 0; common = 1 |
Only vertex 1 has an edge from both queried vertices. |
| 3 | result.append([bool(matrix[left][right]), common]) |
matrix[0][2] = 0; result = [[False, 1]] |
Sharing a neighbor does not imply a direct edge. |
| 4 | common = sum(a and b for a, b in zip(matrix[left], matrix[right])) |
left = right = 1; contributions = 1, 0, 1; common = 2 |
A self query compares the row with itself and counts its present neighbors. |
| 5 | result.append([bool(matrix[left][right]), common]); return result |
matrix[1][1] = 0; result = [[False, 1], [False, 2]] |
The diagonal describes self-loop state independently from the row’s degree. |
| Output | |
|---|---|
| 1 | [[False, 1], [False, 2]] |
| 2 | [] |
Edge existence and common-neighbor count answer separate questions. In this 0/1 Lab, a and b contributes exactly zero or one; weighted values would require an explicit boolean conversion rather than relying on the operand-returning and operator.
Choose a matrix when V is small, density is high, or arbitrary edge lookup dominates. Choose an adjacency list when the graph is sparse or algorithms repeatedly enumerate actual neighbors. For weighted graphs, choose a sentinel distinct from valid zero-weight edges.
[[0] * V] * V aliases rows and mirrors unintended updates.State what a cell and diagonal mean, then justify the O(V squared) memory purchase with density or query requirements. Separate constant edge lookup from linear neighbor enumeration.
Build Graph Representations(opens in a new tab) compares storage forms. Validate a Partial Sudoku(opens in a new tab) uses matrix-like coordinate constraints, though its relationships are implicit rather than edges.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Adjacency Matrix itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Build a V-vertex edge matrix | O(V * V + E) | O(V * V + E) | Initialize every cell and write two positions per input edge; duplicates overwrite boolean state. |
| Query edge existence | O(1) | O(1) | Valid endpoints in square indexed storage. |
| Return q common-neighbor summaries | O(q * V) | O(q * V) | The actual query Lab scans V columns per query and stores one fixed-size summary each. |
O(V * V) for build a v-vertex edge matrix; O(1) for query edge existence; O(q) for return q common-neighbor summaries.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
A single edge assignment changes the same column in every aliased row.
Prevent it: Allocate each vertex row independently.
matrix = [[0] * vertex_count] * vertex_count
matrix[0][1] = 1matrix = [[0] * vertex_count for _ in range(vertex_count)]
matrix[0][1] = 1Where you will hit this: Build Graph Representations(opens in a new tab)
One indexed write creates only the source-to-target direction.
Prevent it: Write the reversed ordered pair for an undirected edge.
matrix[left][right] = 1matrix[left][right] = 1
matrix[right][left] = 1Where you will hit this: Build Graph Representations(opens in a new tab)
Boolean conversion cannot distinguish a zero weight from no edge. The separate weighted contract needs an absence sentinel.
Prevent it: Use a sentinel such as None that is outside the valid weight domain.
has_edge = bool(weighted[0][1])has_edge = weighted[0][1] is not NoneWhere you will hit this: Validate a Partial Sudoku(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27