/311. Sparse Matrix Multiplication

311. Sparse Matrix Multiplication

Medium
Arrays69.3% acceptance

Given two matrices, matrix_a and matrix_b, compute their product matrix_c = matrix_a x matrix_b. Both matrices may contain many zero elements. Return the resulting matrix_c as a list of lists. Assume matrix_a has dimensions m x n and matrix_b has dimensions n x p.

Example 1

Input: matrix_a = [[0, 2], [3, 0]] matrix_b = [[1, 0], [0, 4]]

Output: [[0, 8], [3, 0]]

Explanation: matrix_c[0][0] = 0*1 + 2*0 = 0; matrix_c[0][1] = 0*0 + 2*4 = 8; matrix_c[1][0] = 3*1 + 0*0 = 3; matrix_c[1][1] = 3*0 + 0*4 = 0.

Example 2

Input: matrix_a = [[1, 0, 0], [0, 0, 2]] matrix_b = [[1, 2], [0, 3], [4, 0]]

Output: [[1, 2], [8, 0]]

Explanation: matrix_c[0][0] = 1*1 + 0*0 + 0*4 = 1; matrix_c[0][1] = 1*2 + 0*3 + 0*0 = 2; matrix_c[1][0] = 0*1 + 0*0 + 2*4 = 8; matrix_c[1][1] = 0*2 + 0*3 + 2*0 = 0.

Constraints

  • 1 <= len(matrix_a) <= 100
  • 1 <= len(matrix_a[0]) <= 100
  • 1 <= len(matrix_b) <= 100
  • 1 <= len(matrix_b[0]) <= 100
  • len(matrix_a[0]) == len(matrix_b)
  • All elements in matrix_a and matrix_b are integers in the range [-100, 100]
Python (current runtime)

Case 1

Input: matrix_a = [[0, 0], [5, 6]] matrix_b = [[7, 8], [0, 9]]

Expected: [[0, 0], [35, 86]]

Case 2

Input: matrix_a = [[2, 0, 1], [0, 0, 0]] matrix_b = [[1, 0], [0, 3], [4, 5]]

Expected: [[6, 5], [0, 0]]

Case 3

Input: matrix_a = [[1]] matrix_b = [[2]]

Expected: [[2]]