311. Sparse Matrix Multiplication
Medium ↗ Open on LeetCode Source: Misc
Quick review
- Pattern
- Math & Geometry
- Time
- O(m*n*k)
- Space
- O(m*n)
Standard Solution (C++)
SummaryGiven two matrices mat1 (m x k) and mat2 (k x n), compute their matrix product and return the resulting m x n matrix. The inputs are sparse, meaning most entries are zero, so the solution should skip unnecessary multiplications.
Approach
- Use the standard triple-loop matrix multiplication order: rows of mat1, shared dimension k, then columns of mat2.
- Before the innermost loop, skip any row-column pair where
mat1[i][j] == 0— this avoids iterating over all n columns for zero rows. - Optionally also skip
mat2[j][l] == 0in the innermost loop for additional savings. - This sparsity-aware pruning keeps the worst-case at O(m·k·n) but dramatically cuts average work when the matrices are sparse.
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2) {
int m = mat1.size(); // rows of mat1
int k = mat1[0].size(); // cols of mat1 == rows of mat2
int n = mat2[0].size(); // cols of mat2
vector<vector<int>> result(m, vector<int>(n, 0));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < k; ++j) {
// Skip entire column sweep when mat1 entry is zero
if (mat1[i][j] == 0) continue;
for (int l = 0; l < n; ++l) {
// Skip multiplication when mat2 entry is zero
if (mat2[j][l] == 0) continue;
result[i][l] += mat1[i][j] * mat2[j][l];
}
}
}
return result;
}
};
Time O(m · k · n) worst case; much less in practice for sparse inputs Space O(m · n) for the output matrix
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2) {
int m=mat1.size();
int k=mat1[0].size();
int n=mat2[0].size();
vector<vector<int>> res(m, vector<int>(n, 0));
for(int i=0; i<m; ++i){
for(int j=0; j<k; ++j){
if(mat1[i][j]==0){
continue;
}
for(int l=0; l<n; ++l){
if(mat2[j][l]==0){
continue;
}
res[i][l]+=mat1[i][j]*mat2[j][l];
}
}
}
return res;
}
};
// m*k, k*n
// for each element, we do k multiplication
// m*n elements, so m*n*k multiplication
// Time Complexity: O(m*n*k), where m, n, and k are the dimensions of the input matrices.
// Space Complexity: O(m*n) for the result matrix. Time O(m*n*k) Space O(m*n)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.