Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 311: Sparse Matrix Multiplication

ArrayHash TableMatrix

LeetCode 311 Solution Explanation

Explanation:

To perform matrix multiplication for sparse matrices, we can optimize the process by only computing and storing the non-zero elements. The algorithm involves iterating through the non-zero elements of the first matrix and multiplying them with the corresponding elements in the second matrix to compute the result matrix.

  1. Iterate through the non-zero elements of the first matrix, and for each non-zero element A[i][j], iterate through the corresponding row in the second matrix B[j][k].
  2. Multiply A[i][j] with B[j][k] and add the result to the corresponding element in the result matrix C[i][k].
  3. Repeat this process for all non-zero elements in the first matrix.
  4. The resulting matrix C will be the product of the two sparse matrices.

Time complexity:

  • Let n be the number of rows in the first matrix, m be the number of columns in the first matrix, and p be the number of columns in the second matrix.
  • The time complexity of this algorithm is O(n * m * p), as we iterate through the non-zero elements of the matrices.

Space complexity:

  • We only store the non-zero elements and their positions in the result matrix, so the space complexity is O(n * p).

:

LeetCode 311 Solutions in Java, C++, Python

class Solution {
    public int[][] multiply(int[][] A, int[][] B) {
        int n = A.length;
        int m = A[0].length;
        int p = B[0].length;
        
        int[][] C = new int[n][p];
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (A[i][j] != 0) {
                    for (int k = 0; k < p; k++) {
                        if (B[j][k] != 0) {
                            C[i][k] += A[i][j] * B[j][k];
                        }
                    }
                }
            }
        }
        
        return C;
    }
}

Interactive Code Editor for LeetCode 311

Improve Your LeetCode 311 Solution

Use the editor below to refine the provided solution for LeetCode 311. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems