Sparse matrix multiplication
Background
Many real matrices — graph adjacency matrices, one-hot encodings, term-document matrices — are mostly zeros. Sparse matrix multiplication computes the product while skipping the zero entries, so the cost scales with the number of non-zeros instead of the full of dense multiplication. It is a core primitive in graph algorithms, NLP pipelines, and recommender systems.
Problem statement
Implement sparse_matmul(A, B) that returns the product , computed by iterating only over non-zero entries. For of shape and of shape :
Skip any term where (and, ideally, where ).
Input
A—list[list[float]]of shape(m, k).B—list[list[float]]of shape(k, n). (A's column count equalsB's row count.)
Output
Returns list[list[float]] of shape (m, n): the product .
Examples
Example 1
Input: A = [[1, 0, 0], [-1, 0, 3]], B = [[7, 0, 0], [0, 0, 0], [0, 0, 1]]
Output: [[7, 0, 0], [-7, 0, 3]]
Explanation: only the non-zero products contribute — , , and ; every other entry stays 0.
Constraints
- Skip multiplications where the left factor is zero (an inner skip on is a further optimisation).
- The result has shape
(m, n); initialise it with zeros. - The numeric result must equal the dense product
A @ B.
Notes
- The speedup comes from touching only non-zeros: for density the work is roughly instead of .
- Production libraries store sparse matrices in CSR/CSC formats, which make enumerating "only the non-zeros" an -per-element operation.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Reference example small dense product
- •Example contraction with a zero entry
- •Sample all-ones matrix times a matrix