LeetCode – Sparse Matrix Multiplication (Java)

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.

1. Naive Method

We can implement Sum(A_ik * B_kj) -> C_ij as a naive solution.

public int[][] multiply(int[][] A, int[][] B) {
    //validity check
 
    int[][] C = new int[A.length][B[0].length];
 
    for(int i=0; i<C.length; i++){
        for(int j=0; j<C[0].length; j++){
            int sum=0;
            for(int k=0; k<A[0].length; k++){
                sum += A[i][k]*B[k][j];
            }
            C[i][j] = sum;
        }
    }
 
    return C;
}

Time complexity is O(n^3).

2. Optimized Method

From the formula: Sum(A_ik * B_kj) -> C_ij

We can see that when A_ik is 0, there is no need to compute B_kj. So we switch the inner two loops and add a 0-checking condition.

public int[][] multiply(int[][] A, int[][] B) {
    //validity check
 
    int[][] C = new int[A.length][B[0].length];
 
    for(int i=0; i<C.length; i++){
        for(int k=0; k<A[0].length; k++){
            if(A[i][k]!=0){
                for(int j=0; j<C[0].length; j++){
                    C[i][j] += A[i][k]*B[k][j];
                }
            }
        }
    }
 
    return C;
}

Since the matrix is sparse, time complexity is ~O(n^2) which is much faster than O(n^3).

3 thoughts on “LeetCode – Sparse Matrix Multiplication (Java)”

  1. I am unable to understand how the optimized solution works. If A[0][0] = 0, then C[0][0] = A[0][0] * B[0][0] + A[0][1] * B[1][0]. In that case, we still need to iterate each element. Can some one explain how this works?

Leave a Comment