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.
Examples
Example 1:
$$ \begin{bmatrix} 1 & 0 & 0 \\ -1 & 0 & 3 \end{bmatrix}
\quad \mathbf{X} \quad
\begin{bmatrix} 7 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 1 \end{bmatrix}
\quad \mathbf{=} \quad
\begin{bmatrix} 7 & 0 & 0 \\ -7 & 0 & 3 \end{bmatrix} $$
| |
Solution
Method 1 - Use set to store non-zero elements
The problem requires multiplying two sparse matrices mat1 and mat2. Sparse matrices have a majority of their elements as zeros; hence, efficient storage and computation by focusing only on non-zero elements is essential to reduce time complexity.
Approach
- Create an output matrix: Initialize a matrix
answith dimensionsm x n. - Sparse Matrix Representation: Instead of storing the entire matrices, use dictionaries or lists to store only the non-zero elements.
- Matrix Multiplication:
- Populate the
ansmatrix only by multiplying and adding the non-zero elements in the appropriate positions.
- Populate the
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(m * k * n) - 🧺 Space complexity:
O(m * n)