KatInterview

311. Sparse Matrix Multiplication

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to multiply two sparse matrices, mat1 of size m x k and mat2 of size k x n. A sparse matrix is a matrix where most elements are zero. The standard matrix multiplication algorithm calculates each element res[i][j] of the result matrix by taking the dot product of the i-th row of mat1 and the j-th column of mat2. This involves three nested loops and has a time complexity of O(m * k * n). For sparse matrices, this approach is inefficient because it performs many multiplications with zero, which do not contribute to the final sum.

Solution

Sparse Matrix Multiplication in Python

class Solution:
    def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:
        m, k, n = len(mat1), len(mat1[0]), len(mat2[0])

        # Create a sparse representation of mat2.
        # sparse_mat2[r] will store tuples of (value, column_index) for non-zero elements in row r of mat2.
        sparse_mat2 = [[] for _ in range(k)]
        for r in range(k):
            for c in range(n):
                if mat2[r][c] != 0:
                    sparse_mat2[r].append((mat2[r][c], c))
        
        # Initialize the result matrix with zeros.
        result = [[0] * n for _ in range(m)]

        # Perform the multiplication using the sparse representation of mat2.
        for i in range(m):
            for l in range(k):
                # If the element in mat1 is non-zero, it will contribute to the result.
                if mat1[i][l] != 0:
                    val1 = mat1[i][l]
                    # Multiply val1 with all non-zero elements in the l-th row of mat2.
                    for val2, j in sparse_mat2[l]:
                        result[i][j] += val1 * val2
        
        return result

Sparse Matrix Multiplication in Java

class Solution {
    public int[][] multiply(int[][] mat1, int[][] mat2) {
        int m = mat1.length;
        int k = mat1[0].length;
        int n = mat2[0].length;

        // Create a sparse representation of mat2.
        // sparseMat2.get(r) will store pairs of [value, columnIndex] for non-zero elements in row r of mat2.
        List<List<int[]>> sparseMat2 = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            sparseMat2.add(new ArrayList<>());
        }

        for (int i = 0; i < k; i++) {
            for (int j = 0; j < n; j++) {
                if (mat2[i][j] != 0) {
                    sparseMat2.get(i).add(new int[]{mat2[i][j], j});
                }
            }
        }

        // Initialize the result matrix with zeros.
        int[][] result = new int[m][n];

        // Perform the multiplication using the sparse representation of mat2.
        for (int i = 0; i < m; i++) {
            for (int l = 0; l < k; l++) {
                // If the element in mat1 is non-zero, it will contribute to the result.
                if (mat1[i][l] != 0) {
                    // Multiply mat1[i][l] with all non-zero elements in the l-th row of mat2.
                    for (int[] pair : sparseMat2.get(l)) {
                        int val2 = pair[0];
                        int j = pair[1];
                        result[i][j] += mat1[i][l] * val2;
                    }
                }
            }
        }

        return result;
    }
}

Sparse Matrix Multiplication in C++

class Solution {
public:
    vector<vector<int>> multiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2) {
        int m = mat1.size();
        int k = mat1[0].size();
        int n = mat2[0].size();

        // Create a sparse representation of mat2 to optimize multiplication.
        // sparse_mat2[r] will store pairs of (value, column_index) for non-zero elements in row r of mat2.
        vector<vector<pair<int, int>>> sparse_mat2(k);
        for (int i = 0; i < k; ++i) {
            for (int j = 0; j < n; ++j) {
                if (mat2[i][j] != 0) {
                    sparse_mat2[i].push_back({mat2[i][j], j});
                }
            }
        }

        // Initialize the result matrix with zeros.
        vector<vector<int>> result(m, vector<int>(n, 0));

        // Perform the multiplication using the sparse representation of mat2.
        for (int i = 0; i < m; ++i) {
            for (int l = 0; l < k; ++l) {
                // If the element in mat1 is non-zero, it will contribute to the result.
                if (mat1[i][l] != 0) {
                    // Multiply mat1[i][l] with all non-zero elements in the l-th row of mat2.
                    for (auto const& [val2, j] : sparse_mat2[l]) {
                        result[i][j] += mat1[i][l] * val2;
                    }
                }
            }
        }

        return result;
    }
};

Sparse Matrix Multiplication in TypeScript

function multiply(mat1: number[][], mat2: number[][]): number[][] {
    const m = mat1.length;
    const k = mat1[0].length;
    const n = mat2[0].length;

    // Create a sparse representation of mat2.
    // sparseMat2[r] will store objects {val, col} for non-zero elements in row r of mat2.
    const sparseMat2: { val: number, col: number }[][] = Array.from({ length: k }, () => []);
    for (let r = 0; r < k; r++) {
        for (let c = 0; c < n; c++) {
            if (mat2[r][c] !== 0) {
                sparseMat2[r].push({ val: mat2[r][c], col: c });
            }
        }
    }

    // Initialize the result matrix with zeros.
    const result: number[][] = Array.from({ length: m }, () => Array(n).fill(0));

    // Perform the multiplication using the sparse representation of mat2.
    for (let i = 0; i < m; i++) {
        for (let l = 0; l < k; l++) {
            // If the element in mat1 is non-zero, it will contribute to the result.
            if (mat1[i][l] !== 0) {
                const val1 = mat1[i][l];
                // Multiply val1 with all non-zero elements in the l-th row of mat2.
                for (const pair of sparseMat2[l]) {
                    const { val: val2, col: j } = pair;
                    result[i][j] += val1 * val2;
                }
            }
        }
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.