LeetCode 0311. Sparse Matrix Multiplication Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0311. Sparse Matrix Multiplication

Description

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.

 

Example 1:

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

Example 2:

Input: mat1 = [[0]], mat2 = [[0]]
Output: [[0]]

 

Constraints:

  • m == mat1.length
  • k == mat1[i].length == mat2.length
  • n == mat2[i].length
  • 1 <= m, n, k <= 100
  • -100 <= mat1[i][j], mat2[i][j] <= 100

Solutions

Solution 1: Direct Multiplication

We can directly calculate each element in the result matrix according to the definition of matrix multiplication.

The time complexity is O(m × n × k), and the space complexity is O(m × 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.

PythonJavaC++GoTypeScript
class Solution: def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: m, n = len(mat1), len(mat2[0]) ans = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): for k in range(len(mat2)): ans[i][j] += mat1[i][k] * mat2[k][j] return ans(code-box)

Solution 2: Preprocessing

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 ith row of matrix mat1, and g2[i] represents the column index and value of all non-zero elements in the ith 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] × 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 × n × k), and the space complexity is O(m × 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.

PythonJavaC++GoTypeScript
class Solution: def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]: def f(mat: List[List[int]]) -> List[List[int]]: g = [[] for _ in range(len(mat))] for i, row in enumerate(mat): for j, x in enumerate(row): if x: g[i].append((j, x)) return g g1 = f(mat1) g2 = f(mat2) m, n = len(mat1), len(mat2[0]) ans = [[0] * n for _ in range(m)] for i in range(m): for k, x in g1[i]: for j, y in g2[k]: ans[i][j] += x * y return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !