Given two sparse matricesmat1 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.
By definition each \((i,j)\) is a \(k\)-fold inner product; \(O(mnk)\) is acceptable under the limits. Zeros still participate in the triple loop.
Write the three loops first so the product is correct, then skip zeros in the next method.
We can directly calculate each element in the result matrix according to the definition of matrix multiplication.
The time complexity is \(O(m \times n \times k)\), and the space complexity is \(O(m \times n)\). Where \(m\) and \(n\) are the number of rows of matrix \(mat1\) and the number of columns of matrix \(mat2\) respectively, and \(k\) is the number of columns of matrix \(mat1\) or the number of rows of matrix \(mat2\).
Method 1 still multiplies zeros. Compress each matrix to per-row lists of nonzero \((column,value)\), and accumulate \(ans[i][j]\mathrel{+}=x\cdot y\) only for those pairs. Zeros never enter the inner loop; the worst case remains \(O(mnk)\).
We can preprocess the sparse representation of the two matrices, i.e., \(g1[i]\) represents the column index and value of all non-zero elements in the \(i\)th row of matrix \(mat1\), and \(g2[i]\) represents the column index and value of all non-zero elements in the \(i\)th row of matrix \(mat2\).
Next, we traverse each row \(i\), traverse each element \((k, x)\) in \(g1[i]\), traverse each element \((j, y)\) in \(g2[k]\), then \(mat1[i][k] \times mat2[k][j]\) will correspond to \(ans[i][j]\) in the result matrix, and we can accumulate all the results.
The time complexity is \(O(m \times n \times k)\), and the space complexity is \(O(m \times n)\). Where \(m\) and \(n\) are the number of rows of matrix \(mat1\) and the number of columns of matrix \(mat2\) respectively, and \(k\) is the number of columns of matrix \(mat1\) or the number of rows of matrix \(mat2\).