Sparse Matrix Multiplication - Problem
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.
A sparse matrix is a matrix in which most of the elements are zero. The key insight is to avoid unnecessary multiplications with zero values to optimize performance.
Input & Output
Example 1 — Basic Sparse Matrix
$
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]]
💡 Note:
Row 0: 1×7 + 0×0 + 0×0 = 7, 1×0 + 0×0 + 0×0 = 0, 1×0 + 0×0 + 0×1 = 0. Row 1: -1×7 + 0×0 + 3×0 = -7, -1×0 + 0×0 + 3×0 = 0, -1×0 + 0×0 + 3×1 = 3
Example 2 — Dense Matrix
$
Input:
mat1 = [[1,0]], mat2 = [[7],[0]]
›
Output:
[[7]]
💡 Note:
Single element multiplication: 1×7 + 0×0 = 7
Example 3 — All Zeros Result
$
Input:
mat1 = [[0,1],[0,0]], mat2 = [[1,0],[0,0]]
›
Output:
[[0,0],[0,0]]
💡 Note:
Row 0: 0×1 + 1×0 = 0, 0×0 + 1×0 = 0. Row 1: 0×1 + 0×0 = 0, 0×0 + 0×0 = 0
Constraints
- m == mat1.length
- k == mat1[i].length == mat2.length
- n == mat2[i].length
- 1 ≤ m, n, k ≤ 100
- -100 ≤ mat1[i][j], mat2[i][j] ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two sparse matrices with many zero elements
2
Process
Standard matrix multiplication but skip zero multiplications
3
Output
Resulting matrix from mat1 × mat2
Key Takeaway
🎯 Key Insight: Only multiply non-zero elements to achieve significant speedup for sparse matrices
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code