The standard O(MKN) multiplication can be optimized for sparse matrices by only iterating over non-zero elements.
- Initialize
resmatrix of sizem x nwith 0s. - Iterate
ifrom 0 tom-1. - Iterate
kfrom 0 tok-1. - If
mat1[i][k] != 0:- Only then iterate
jfrom 0 ton-1. - If
mat2[k][j] != 0:res[i][j] += mat1[i][k] * mat2[k][j]. This structure minimizes unnecessary multiplications.
- Only then iterate
- Time Complexity: O(M * K * N) worst case, but significantly faster for sparse matrices.
- Space Complexity: O(M * N) for the result.
def multiply(mat1, mat2):
m, k_dim = len(mat1), len(mat1[0])
n = len(mat2[0])
res = [[0] * n for _ in range(m)]
for i in range(m):
for k in range(k_dim):
if mat1[i][k] != 0:
for j in range(n):
if mat2[k][j] != 0:
res[i][j] += mat1[i][k] * mat2[k][j]
return res