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).

Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • ryanlr

    It’s not compressed. Just take shortcut to skip computation when an element is 0.

  • nik vamv

    Is this compressed sparse row multiplication ?