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.
This problem ships 4 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Reference example (LeetCode 311)
- •Matches dense matrix multiplication
- •Result has shape (rows of A, cols of B)
- •Multiplying by a zero matrix gives all zeros