311. Sparse Matrix Multiplication

Given twosparse matrices A and B, return the result of AB.

You may assume that A's column number is equal to B's row number.

Example:

Input:

A = [
  [ 1, 0, 0],
  [-1, 0, 3]
]


B = [
  [ 7, 0, 0 ],
  [ 0, 0, 0 ],
  [ 0, 0, 1 ]
]

Output:

     |  1 0 0 |   | 7 0 0 |   |  7 0 0 |
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
                  | 0 0 1 |

Thoughts:

  1. Idea from a CMU lecture.: A sparse matrix can be represented as a sequence of rows, each of which is a sequence of (column-number, value) pairs of the nonzero values in the row.

  2. Time Complexity Proposal: O(m*n + k*nB). Here k: number of non-empty elements in A. So in the worst case (dense matrix), it's O(m*n*nB)(from here)

Code:

Code: improvements: Definition of matrix multiplication: No extra space required

Last updated

Was this helpful?