Implement a Sparse Matrix Class
Company: Pinterest
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates the ability to design and implement efficient sparse data structures and perform matrix operations, testing knowledge of sparse matrix representation, linear algebra operations (addition and multiplication), and algorithmic complexity analysis.
Constraints
- 0 <= number of rows, number of columns <= 200
- All input matrices are rectangular
- -10^6 <= matrix[i][j] <= 10^6
- For addition, both matrices must have the same dimensions
- For multiplication, matrix_a columns must equal matrix_b rows
Examples
Input: ("dense", [[0,0,3],[0,0,0],[4,0,5]], None)
Expected Output: [[0,0,3],[0,0,0],[4,0,5]]
Explanation: The sparse structure stores only the three non-zero entries and reconstructs the same dense matrix.
Input: ("add", [[1,0,0],[0,2,0]], [[0,3,0],[4,0,0]])
Expected Output: [[1,3,0],[4,2,0]]
Explanation: Add corresponding cells. Zeros do not need to be stored internally.
Input: ("add", [[5,0],[0,0]], [[-5,0],[0,0]])
Expected Output: [[0,0],[0,0]]
Explanation: The only non-zero values cancel out, so the sparse result has no stored entries.
Input: ("multiply", [[1,0,2],[0,3,0]], [[0,4],[5,0],[0,6]])
Expected Output: [[0,16],[15,0]]
Explanation: Only matching non-zero pairs contribute: row 0 gives 16 in column 1, and row 1 gives 15 in column 0.
Input: ("multiply", [[1,2]], [[1,2]])
Expected Output: []
Explanation: A 1x2 matrix cannot be multiplied by another 1x2 matrix because the inner dimensions do not match.
Input: ("dense", [], None)
Expected Output: []
Explanation: An empty matrix remains empty after sparse conversion and reconstruction.
Hints
- A dictionary keyed by `(row, column)` lets you store only non-zero entries and look them up efficiently.
- For multiplication, group non-zero values of the second matrix by row so that each non-zero `(i, k)` in the first matrix only combines with useful entries.