Search⌘ K
AI Features

Sparse Matrix Multiplication

Explore how to multiply two sparse matrices by representing them as hashmaps to store non-zero elements. This lesson teaches you to optimize matrix multiplication, handle constraints, and analyze time and space complexity for better coding interview solutions.

Description

We have two sparse matrices, A and B.

“A sparse matrix is one in which most of the elements are zero.”

You need to multiply the two matrices and return the output matrix. You can assume that A’s column number is equal to B’s row number.

Constraints

The following are some constraints:

  • 1 <= A.length, B.length <= 100
  • 1 <= A[i].length, B[i].length <= 100
  • -100 <= A[i][j], B[i][j] <= 100

Let’s review this scenario using the example below:

Coding exercise

C++ 17
std::vector<std::vector<int>> multiply(std::vector<std::vector<int>>& A, std::vector<std::vector<int>>& B){
// Write your code here
return {};
}
Sparse matrix multiplication

Solution

We have two sparse matrices, meaning most of the matrices’ elements are zero. We can represent the input matrices as hashmaps, and only save ...