NeetCode #24LC-311MediumArrays & HashingNC Algo100
← Back to All Problems#24 · #311 · Sparse Matrix Multiplication(稀疏矩阵的乘法)
📌 Problem Statement & Constraints
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 the multiplication is always possible. Constraints: 1 <= m, k, n <= 100, -100 <= mat1[i][j], mat2[i][j] <= 100.💡 Core Algorithmic Approaches
- The textbook triple loop is O(m * k * n), but for sparse inputs most entries are zero and contribute nothing.
- Precompute, for each row of
mat1, the list of(column, value)pairs where the value is non-zero. - For each such pair, add
value * mat2[column][j]tores[row][j]for everyj. - Skipping zero entries in
mat1is the main saving; you can additionally storemat2column-wise to skip its zeros.
💻 Benchmark Python3 Implementation
class Solution:
def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:
m, k, n = len(mat1), len(mat2), len(mat2[0])
res = [[0] * n for _ in range(m)]
# index the non-zero entries of mat1 row by row
nz1 = [[(t, v) for t, v in enumerate(mat1[i]) if v] for i in range(m)]
for i in range(m):
for t, v in nz1[i]: # only non-zero terms contribute
row2 = mat2[t]
for j in range(n):
if row2[j]:
res[i][j] += v * row2[j]
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(m * k * n) worst case, but proportional to the number of non-zero entries in practice: for each non-zero of mat1 we touch one row of mat2.
💾 Space Complexity
O(m + nnz(mat1)) for the non-zero index, plus O(m * n) for the output.
⚠️ Interview Pitfalls & Follow-ups
- Writing the naive triple loop without skipping zeros: correct but wasteful for the sparse inputs the problem targets.
- Assuming
mat1[i][j] == 0implies the whole product row is zero: only that single term vanishes; other terms still contribute. - Reusing the input matrix for the output: the shapes differ whenever
n != k. - Forgetting the
kdimension: it is the shared inner dimension and must be iterated in the accumulation.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
稀疏矩阵的乘法
给定两个 稀疏 矩阵 mat1(尺寸 m × k)和 mat2(尺寸 k × n),返回它们的乘积 mat1 × mat2。你可以假设 mat1 的列数等于 mat2 的行数。约束:1 ≤ m, k, n ≤ 100;-100 ≤ mat1[i][j], mat2[i][j] ≤ 100;矩阵中非零元素很少。
核心要点
- 朴素三重循环 :标准矩阵乘法,O(m · k · n)。当矩阵稀疏时,大量乘法是「0 × 0」的无用功。
- 跳过零元素(标准优化) :预处理 mat1,把每行的非零元素收集成 [(列下标, 值)] ;三重循环中只遍历这些非零项。
- 内层也要判零 :对 mat2[t][j] 为 0 的情况直接跳过,避免无意义的乘法与加法。
- 为什么这样更快 :设 mat1 非零元素数为 z1,mat2 每行平均非零数为 z2,则复杂度约为 O(m · z1/m · n) 但实际只对非零项相乘,稀疏时远优于朴素算法。
常见陷阱
- 以为稀疏优化改变了最坏复杂度 :最坏情况(全非零)仍是 O(m · k · n)。面试中要如实说明这一点,不要声称「优化到了 O(m · n)」。
- 忘记跳过 mat2 的零元素 :只优化 mat1 而内层全遍历,收益会减半。
- 用字典存非零元素 :也可以,但本题用「每行的列表」更简单且缓存更友好。
- 结果矩阵维度写错 :结果应为 m × n(mat1 的行数 × mat2 的列数),写成 m × k 或 k × n 都会出错。
参考实现
class Solution:
def multiply(self, mat1: list[list[int]], mat2: list[list[int]]) -> list[list[int]]:
m, k = len(mat1), len(mat1[0])
n = len(mat2[0])
res = [[0] * n for _ in range(m)]
# 预处理 mat1:每行的非零元素 (列下标, 值)
nonzero = [[] for _ in range(m)]
for i in range(m):
for t in range(k):
if mat1[i][t] != 0:
nonzero[i].append((t, mat1[i][t]))
for i in range(m):
for t, v in nonzero[i]: # 只遍历 mat1 的非零项
row2 = mat2[t]
for j in range(n):
if row2[j] != 0: # 跳过 mat2 的零元素
res[i][j] += v * row2[j]
return res