Sparse Matrix Multiplication - Problem

You're working with sparse matrices - matrices where most elements are zero. Given two sparse matrices mat1 of size m × k and mat2 of size k × n, your task is to compute their matrix multiplication mat1 × mat2.

The key insight is that in sparse matrices, we can skip multiplications involving zero elements to achieve better performance than the standard O(m×n×k) matrix multiplication algorithm.

Matrix Multiplication Refresher:
The element at position (i,j) in the result matrix equals the dot product of row i from mat1 and column j from mat2:
result[i][j] = sum(mat1[i][p] * mat2[p][j] for p in range(k))

Example:
If mat1 = [[1,0,0],[-1,0,3]] and mat2 = [[7,0,0],[0,0,0],[0,0,1]], then:
result[0][0] = 1×7 + 0×0 + 0×0 = 7
result[1][2] = -1×0 + 0×0 + 3×1 = 3

Input & Output

example_1.py — Basic Sparse Matrices
$ 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: mat1[0][0] * mat2[0][0] = 1 * 7 = 7 for result[0][0]. mat1[1][0] * mat2[0][0] = -1 * 7 = -7 and mat1[1][2] * mat2[2][2] = 3 * 1 = 3 for result[1][0] and result[1][2] respectively. All other multiplications involve zeros.
example_2.py — Dense Result from Sparse Inputs
$ Input: mat1 = [[1,1]], mat2 = [[1],[1]]
Output: [[2]]
💡 Note: Single element result: mat1[0][0] * mat2[0][0] + mat1[0][1] * mat2[1][0] = 1 * 1 + 1 * 1 = 2
example_3.py — All Zeros Matrix
$ Input: mat1 = [[0,0],[0,0]], mat2 = [[1,2],[3,4]]
Output: [[0,0],[0,0]]
💡 Note: When mat1 contains all zeros, the result is always a zero matrix regardless of mat2 values. The optimized solution will skip all computations.

Constraints

  • m, k, n ≤ 100
  • -100 ≤ mat1[i][j], mat2[i][j] ≤ 100
  • The number of zeros in the matrices is in the range [0, (m×k + k×n)]
  • Matrices are sparse - most elements are zero

Visualization

Tap to expand
Sparse Matrix MultiplicationMatrix A (sparse)500203001040Matrix BResult MatrixOnly process circled elements!Skip all gray zerosPerformance GainStandard: O(m × n × k) operationsOptimized: O(non-zeros × n) operationsUp to 90% faster for sparse matrices!
Understanding the Visualization
1
Identify Sparsity
Locate non-zero elements in the first matrix
2
Skip Zeros
Avoid computations when mat1[i][k] = 0
3
Process Non-Zeros
Only multiply and accumulate for non-zero elements
4
Build Result
Construct the result matrix efficiently
Key Takeaway
🎯 Key Insight: Skip multiplications involving zero elements to achieve dramatic performance improvements on sparse matrices
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
52.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen