Sparse Matrix Multiplication Problem
Description
LeetCode Problem 311.
Given two sparse matrices mat1 of size m x k and mat2 of size k x n, return the result of mat1 x mat2. You may assume that multiplication is always possible.
Example 1:

Input: mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
Output: [[7,0,0],[-7,0,3]]
Example 2:
Input: mat1 = [[0]], mat2 = [[0]]
Output: [[0]]
Constraints:
m == mat1.lengthk == mat1[i].length == mat2.lengthn == mat2[i].length1 <= m, n, k <= 100-100 <= mat1[i][j], mat2[i][j] <= 100
Solution
Approach: Skip the Zeros
By definition, result[i][j] is the sum of mat1[i][r] * mat2[r][j] over all r, and computing that directly takes O(m · k · n) time. In sparse matrices most of those products are 0 * something, so we only want to touch the pairs where both factors are non-zero.
Change the loop order so that each non-zero mat1[i][r] is used once: it contributes mat1[i][r] * mat2[r][j] to result[i][j] for every column j of row r in mat2. So:
- For each row
rofmat2, list the columnsjwheremat2[r][j] != 0. - For each row
iand eachr, skipmat1[i][r]if it is zero. Otherwise, for each listed columnjof rowr, addmat1[i][r] * mat2[r][j]toresult[i][j].
Each product we compute has two non-zero factors, and the result is still exact because the skipped products are all zero.
Complexity: O(m · k + k · n + P) time, where P is the number of pairs of non-zero entries that meet (at most m · k · n, and far fewer when the matrices are sparse), and O(k · n) extra space for the lists of non-zero columns, besides the output.
class Solution:
def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:
m, n = len(mat1), len(mat2[0])
# The non-zero entries of each row of mat2, as (column, value).
nonzero = [[(j, x) for j, x in enumerate(row) if x != 0] for row in mat2]
result = [[0] * n for _ in range(m)]
for i in range(m):
for k, a in enumerate(mat1[i]):
if a == 0:
continue # this entry adds nothing to row i
for j, b in nonzero[k]:
result[i][j] += a * b
return result