Sparse Matrix Multiplication — LeetCode 311 Python Solution

MediumLeetCode PremiumArrayHash TableMatrix
Problem
#311
Reading time
2 min

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

Python
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

Complexity

MeasureComplexity
TimeO(m \times n \times k)
SpaceO(m \times n) auxiliary

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

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 \times n \times k).
What is the space complexity of LeetCode 311. Sparse Matrix Multiplication?
The Python solution on this page uses O(m \times 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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview