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
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