Sparse matrix multiplicationMedium

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 O(mkn)O(mkn) 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 C=ABC = AB, computed by iterating only over non-zero entries. For AA of shape (m,k)(m, k) and BB of shape (k,n)(k, n):

Cij==1kAiBjC_{ij} = \sum_{\ell=1}^{k} A_{i\ell}\, B_{\ell j}

Skip any term where Ai=0A_{i\ell} = 0 (and, ideally, where Bj=0B_{\ell j} = 0).

Input

  • Alist[list[float]] of shape (m, k).
  • Blist[list[float]] of shape (k, n). (A's column count equals B's row count.)

Output

Returns list[list[float]] of shape (m, n): the product ABAB.

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 — C00=17=7C_{00} = 1\cdot 7 = 7, C10=17=7C_{10} = -1\cdot 7 = -7, and C12=31=3C_{12} = 3\cdot 1 = 3; every other entry stays 0.

Constraints

  • Skip multiplications where the left factor AiA_{i\ell} is zero (an inner skip on BjB_{\ell j} 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 ρ\rho the work is roughly O(ρmkn)O(\rho\, mkn) instead of O(mkn)O(mkn).
  • Production libraries store sparse matrices in CSR/CSC formats, which make enumerating "only the non-zeros" an O(1)O(1)-per-element operation.
Python
Loading...

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