Skip to contentKEEP THE CRAFTTHE SANCTUARY

Adjacency Matrix

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…

Adjacency Matrix Code Labs

Mental Model

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.

One Cell per Possible Edge

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.

Build a Symmetric Matrix

Allocate rows independently, then write both directions for each undirected edge. Duplicate edges overwrite the same cells harmlessly when the matrix stores booleans.

Build a Symmetric Edge Matrix

Reference
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 matrix
Practice

Implement 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.

Public tests

  • Verify symmetry and row ownership

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Build a Symmetric Edge Matrix

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 matrix

Use Constant-Time Edge Queries

One 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.

Query Edges and Common Neighbors

Reference
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 result
Practice

Implement 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.

Public tests

  • Verify direct and common-neighbor queries

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Query Edges and Common Neighbors

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 result

Trace Direct Edge Lookup Apart from Row Intersection

Use 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.
Print 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 Matrix or List

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.

Matrix Edge and Reachability Mistakes

  • [[0] * V] * V aliases rows and mirrors unintended updates.
  • Writing one direction for an undirected edge breaks symmetry.
  • Treating a zero cell as absent fails when zero is a valid edge weight.
  • Claiming O(V + E) traversal while scanning V cells for every visited vertex is incorrect.

Explain It in an Interview

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 Version Note

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)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Build a V-vertex edge matrixO(V * V + E)O(V * V + E)Initialize every cell and write two positions per input edge; duplicates overwrite boolean state.
Query edge existenceO(1)O(1)Valid endpoints in square indexed storage.
Return q common-neighbor summariesO(q * V)O(q * V)The actual query Lab scans V columns per query and stores one fixed-size summary each.

Space

O(V * V) for build a v-vertex edge matrix; O(1) for query edge existence; O(q) for return q common-neighbor summaries.

Assumptions

  • Initialize every cell and write two positions per input edge; duplicates overwrite boolean state.
  • Valid endpoints in square indexed storage.
  • The actual query Lab scans V columns per query and stores one fixed-size summary each.

Invariants Worth Saying Aloud

  1. matrix[u][v] belongs to one ordered pair; rows do not alias.
  2. Undirected boolean edge storage is symmetric, including explicit self-loops.
  3. The query Lab counts common neighbors in matching columns of square 0/1 rows.

When To Use Or Avoid Adjacency Matrix

Use It When

  • Use independent-row matrices when direct edge-existence queries justify quadratic storage.
  • Use explicit 0/1 cells for the boolean query Lab.

Choose Another Tool When

  • Use adjacency lists for large sparse graphs and repeated neighbor enumeration.
  • Do not use zero as absence when zero is a valid edge weight.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Sharing one row across every vertex

A single edge assignment changes the same column in every aliased row.

Prevent it: Allocate each vertex row independently.

Avoid

matrix = [[0] * vertex_count] * vertex_count
matrix[0][1] = 1

Use instead

matrix = [[0] * vertex_count for _ in range(vertex_count)]
matrix[0][1] = 1

Leaving an undirected matrix asymmetric

One indexed write creates only the source-to-target direction.

Prevent it: Write the reversed ordered pair for an undirected edge.

Avoid

matrix[left][right] = 1

Use instead

matrix[left][right] = 1
matrix[right][left] = 1

Treating a valid zero-weight edge as absent

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.

Avoid

has_edge = bool(weighted[0][1])

Use instead

has_edge = weighted[0][1] is not None

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.