MediumNo. 0311LeetCode Premium
Sparse Matrix Multiplication — LeetCode 311 Python Solution
- Pattern
- Matrix and Grid
- Topics
- Array, Hash Table, Matrix
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- 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]]
Python solution
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 ansComplexity
- Time
- O(m × n × k)
- Space · auxiliary
- O(m × n)
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 311. Sparse Matrix Multiplication is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0036 | Valid Sudoku | Medium |
| 0037 | Sudoku Solver | Hard |
| 0073 | Set Matrix Zeroes | Medium |
| 0840 | Magic Squares In Grid | Medium |
| 0959 | Regions Cut By Slashes | Medium |
| 1072 | Flip Columns For Maximum Number of Equal Rows | Medium |
Frequently asked questions
- How hard is LeetCode 311. Sparse Matrix Multiplication?
LeetCode 311. Sparse Matrix Multiplication is rated Medium on LeetCode.
- What is the time complexity of LeetCode 311. Sparse Matrix Multiplication?
The Python solution on this page runs in O(m × n × k).
- What is the space complexity of LeetCode 311. Sparse Matrix Multiplication?
The Python solution on this page uses O(m × n) auxiliary space.
- What topics does LeetCode 311. Sparse Matrix Multiplication cover?
LeetCode 311. Sparse Matrix Multiplication is tagged Array, Hash Table and Matrix on LeetCode.
- Is LeetCode 311. Sparse Matrix Multiplication a premium problem?
Yes. LeetCode 311. Sparse Matrix Multiplication is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.