Build a CSR Container and Multiply It by a Dense Vector
Data Structure DesignModel answerLast updated
Design a class that compresses a mostly-zero integer matrix into three CSR arrays, then use it to compute a matrix-vector product in time proportional to the non-zero count.
Compact Storage for a Mostly-Zero Matrix
Feature matrices in machine learning are often almost entirely zeros, so keeping them in a full 2D list wastes a lot of memory. Your task is to write a class SparseMatrix that keeps only the non-zero entries using the Compressed Sparse Row (CSR) layout, and that can multiply the stored matrix by a dense vector without touching the zeros.
What to implement
__init__(self, matrix): takes a regular 2D list of integers and builds three arrays:values: every non-zero entry, listed row by row (left to right within a row).col_indices: for each entry ofvalues, the column it came from.row_ptr: for each row, the position invalueswhere that row's entries begin. It also carries one final element marking the end of the last row.
multiply(self, vector): takes a dense list whose length equals the number of columns, and returns the dense list that is the product of the matrix and the vector.
Limits
- Up to 10,000 rows and 10,000 columns.
- At most 1,000,000 non-zero entries.
- The vector length always equals the column count.
Worked example
# Matrix: [[1, 0, 2],
# [0, 0, 3]]
# Vector: [1, 2, 3]
# CSR form:
# values = [1, 2, 3]
# col_indices = [0, 2, 2]
# row_ptr = [0, 2, 3]
# Product: [1*1 + 2*3, 3*3] = [7, 9]
Cases your code must handle
- A matrix consisting only of zeros.
- A matrix with exactly one non-zero entry.
- An empty (0x0) matrix.
What to cover in your answer
Give the code, explain why the multiplication is correct, and state the time and space cost of both the constructor and multiply. Be ready to discuss how CSR compares with other sparse layouts and how you would extend the idea.
Hints
Hint 1
Think of `row_ptr` as a set of boundaries: row `i` owns the slice of `values` from `row_ptr[i]` up to, but not including, `row_ptr[i+1]`. How many boundaries do you need for R rows?
Hint 2
While scanning each row of the input, append non-zeros to `values` and their column numbers to `col_indices`. Once the row is finished, record the current length of `values` as the next `row_ptr` entry. Start `row_ptr` as `[0]`.
Hint 3
For output row `i`, loop only over `k` in `range(row_ptr[i], row_ptr[i+1])` and add `values[k] * vector[col_indices[k]]`. An empty row gives an empty range, so its result is 0 with no special code.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
CSR stores a matrix as three flat arrays:
values[k]: the k-th non-zero, in row-major order.col_indices[k]: the column ofvalues[k].row_ptr[i]: the index invalueswhere rowibegins. Its length isR + 1, androw_ptr[R] = nnz.
The non-zeros of row i are exactly values[row_ptr[i] : row_ptr[i+1]]. If the two pointers are equal, the row is empty.
Construction
Scan the dense input row by row. For each non-zero cell, append the value and its column index. After finishing a row, push len(values) onto row_ptr. Initialize row_ptr = [0] so that row 0 has a start boundary.
For [[1, 0, 2], [0, 0, 3]]:
| After | values | col_indices | row_ptr |
|---|---|---|---|
| row 0 | [1, 2] | [0, 2] | [0, 2] |
| row 1 | [1, 2, 3] | [0, 2, 2] | [0, 2, 3] |
Multiplication
Output entry i is the dot product of row i with the vector. Terms where the matrix entry is zero add nothing, so we only sum over the stored entries:
result[i] = sum(values[k] * vector[col_indices[k]]
for k in range(row_ptr[i], row_ptr[i+1]))
For the example with vector [1, 2, 3]: row 0 gives 1*1 + 2*3 = 7, row 1 gives 3*3 = 9, so the result is [7, 9].
Why it is correct
The dense formula is sum_j A[i][j] * v[j]. Dropping the zero terms leaves the sum unchanged. Construction writes each row's non-zeros contiguously, with the right column attached, before recording the next boundary, so the range [row_ptr[i], row_ptr[i+1]) contains precisely row i's non-zeros. The sparse sum therefore matches the dense sum term for term.
Code
from typing import List
class SparseMatrix:
def __init__(self, matrix: List[List[int]]):
self.n_rows = len(matrix)
self.n_cols = len(matrix[0]) if matrix else 0
self.values: List[int] = []
self.col_indices: List[int] = []
self.row_ptr: List[int] = [0]
for row in matrix:
if len(row) != self.n_cols:
raise ValueError("All rows must have the same length")
for j, x in enumerate(row):
if x != 0:
self.values.append(x)
self.col_indices.append(j)
self.row_ptr.append(len(self.values))
def multiply(self, vector: List[int]) -> List[int]:
if len(vector) != self.n_cols:
raise ValueError("Vector length must equal number of columns")
values, cols, ptr = self.values, self.col_indices, self.row_ptr
result = [0] * self.n_rows
for i in range(self.n_rows):
total = 0
for k in range(ptr[i], ptr[i + 1]):
total += values[k] * vector[cols[k]]
result[i] = total
return result
Local aliases inside multiply avoid repeated attribute lookups in the hot loop.
Complexity
Let R = rows, C = columns, nnz = non-zero count.
- Construction: O(R·C) time, since every cell of a dense input must be inspected (unavoidable). Extra space is O(nnz + R).
- Multiply: O(R + nnz) time: each stored entry is touched once, and each row costs O(1) overhead even if empty. Output space is O(R).
At 10,000 x 10,000 a dense multiply is about 10^8 operations, while CSR with 10^6 non-zeros needs about 10^6, roughly 100x less. Memory falls from 10^8 cells to about 2·10^6 + 10^4 stored numbers.
Edge cases
- 0x0 matrix:
n_cols = 0,row_ptr = [0], andmultiply([])returns[]. - All zeros:
valuesandcol_indicesare empty androw_ptris all zeros, so the result is[0] * R. - Single non-zero: one stored entry, one non-zero output position.
- Rows with zero columns (
[[], []]): result is[0, 0]. - Empty rows in the middle: equal consecutive pointers give zero iterations, with no special handling.
- Length mismatch: raise
ValueErrorrather than failing with an obscureIndexErroror returning garbage.
Trade-offs and follow-ups
CSR vs COO. COO stores a (row, col, value) triple per entry: 3·nnz numbers. CSR uses 2·nnz + R + 1, which is smaller whenever nnz > R + 1. COO can win when most rows are empty, and it is easier to build, accepts unordered appends, and allows duplicates to be summed later. CSR wins for computation because row slicing is O(1) and access is cache-friendly.
Sparse x sparse (SpGEMM). Store both matrices in CSR and use Gustavson's row-wise method: for each non-zero A[i,k], scale row k of B and accumulate into a per-row accumulator (a dict, or a dense length-C array plus a list of touched columns that is reset after each row). Cost is proportional to the number of scalar multiplications, not to the dense dimensions.
Frequent updates. CSR is poor when the sparsity pattern changes. Inserting a new non-zero shifts the tail of values and col_indices and increments every later row_ptr entry: O(nnz) per insert. Updating an existing non-zero is cheap. For update-heavy workloads, build with a dictionary-of-keys or list-of-lists structure and convert to CSR once the data is stable.
Production note. Use scipy.sparse.csr_matrix or a vectorized NumPy approach rather than Python loops.
Common mistakes
- Making
row_ptrlength R instead of R + 1, which breaks the last row. - Forgetting the initial
0inrow_ptr. - Claiming construction is O(nnz); from a dense input it is O(R·C).
- Special-casing empty rows instead of relying on equal pointers.
- Not validating the vector length.