[LeetCode] 311. Sparse Matrix Multiplication

Given two sparse 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:
A = [
  [ 1, 0, 0],
  [-1, 0, 3]
]

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


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

Thought process:
Create product matrix. Iterate through it and calculate result for each position. This ignores the fact that the matrices are sparse.

Solution 1:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int Arow = A.length;
        int Acolumn = A[0].length;
        int Brow = B.length;
        int Bcolumn = B[0].length;
        
        int[][] product = new int[Arow][Bcolumn];
        for (int i = 0; i < Arow; i++) {
            for (int j = 0; j < Bcolumn; j++) {
                int sum = 0;
                for (int k = 0; k < Acolumn; k++) {
                    sum += A[i][k] * B[k][j];
                }
                product[i][j] = sum;
            }
        }
        return product;
    }
}

Time complexity:
O(A's row * B's column * A's column (which is the same as B's row)). This solution exceeds the time limit.

How do I use the information that the matrices are sparse? Instead of iterating through the product matrix, I can iterate through A, and add the contribution of each number to the result matrix. If A[i][j] == 0, I can just skip the calculation.

Solution 2:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int ARow = A.length;
        int AColumn = A[0].length;
        int BRow = B.length;
        int BColumn = B[0].length;
        
        int[][] product = new int[ARow][BColumn];
        for (int i = 0; i < ARow; i++) {
            for (int j = 0; j < AColumn; j++) {
                if (A[i][j] == 0) {
                    continue;
                }
                for (int k = 0; k < BColumn; k++) {
                    product[i][k] += A[i][j] * B[j][k];
                }
            }
        }
        return product;
    }
}

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula