KatInterview

Build a CSR Container and Multiply It by a Dense Vector

Data Structure DesignModel answer
MediumModel answerData Structure Designsparse-matrixcsrmatrix-vector-multiplication

Last 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

  1. __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 of values, the column it came from.
    • row_ptr: for each row, the position in values where that row's entries begin. It also carries one final element marking the end of the last row.
  2. 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.