Sparse Matrix Multiplication - 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.

A sparse matrix is a matrix in which most of the elements are zero. The key insight is to avoid unnecessary multiplications with zero values to optimize performance.

Input & Output

Example 1 — Basic Sparse Matrix
$ 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]]
💡 Note: Row 0: 1×7 + 0×0 + 0×0 = 7, 1×0 + 0×0 + 0×0 = 0, 1×0 + 0×0 + 0×1 = 0. Row 1: -1×7 + 0×0 + 3×0 = -7, -1×0 + 0×0 + 3×0 = 0, -1×0 + 0×0 + 3×1 = 3
Example 2 — Dense Matrix
$ Input: mat1 = [[1,0]], mat2 = [[7],[0]]
Output: [[7]]
💡 Note: Single element multiplication: 1×7 + 0×0 = 7
Example 3 — All Zeros Result
$ Input: mat1 = [[0,1],[0,0]], mat2 = [[1,0],[0,0]]
Output: [[0,0],[0,0]]
💡 Note: Row 0: 0×1 + 1×0 = 0, 0×0 + 1×0 = 0. Row 1: 0×1 + 0×0 = 0, 0×0 + 0×0 = 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

Visualization

Tap to expand
Sparse Matrix Multiplication INPUT mat1 (2x3) 1 0 0 -1 0 3 mat2 (3x3) 7 0 0 0 0 0 0 0 1 Gray cells = zeros (skipped) White cells = non-zero values Non-zero Zero ALGORITHM STEPS 1 Build Hash Map Store non-zero mat1 elements mat1_map: (0,0):1, (1,0):-1, (1,2):3 row --> [(col, val), ...] 2 Build Hash Map Store non-zero mat2 elements mat2_map: (0,0):7, (2,2):1 3 Multiply Non-zeros Only matching k indices mat1[0][0]*mat2[0][0] = 1*7 = 7 mat1[1][2]*mat2[2][2] = 3*1 = 3 4 Accumulate Results Sum products per cell FINAL RESULT Result Matrix (2x3) 7 0 0 -7 0 3 Output: [[7,0,0],[-7,0,3]] Calculations: res[0][0] = 1*7 = 7 res[1][0] = -1*7 = -7 res[1][2] = 3*1 = 3 All other cells remain 0 OK - Verified Key Insight: Hash maps store only non-zero elements, converting O(m*k*n) to O(nnz1 * nnz2/k) where nnz = non-zeros. For sparse matrices, we skip multiplications involving zeros entirely, making the algorithm much faster. Space: O(nnz) for hash maps | Time: Proportional to actual non-zero multiplications needed. TutorialsPoint - Sparse Matrix Multiplication | Hash Map for Sparse Representation
Asked in
Facebook 15 Google 12 LinkedIn 8 Microsoft 6
89.5K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen