Implement sparse matrix storage, addition, and multiplication
PinterestSoftware Engineer · OnsiteLast updated
This problem tests your ability to design a memory-efficient representation for sparse matrices and implement arithmetic operations while leveraging the sparsity of the data.
Sparse Matrix Operations
In many applications, matrices are very large but contain mostly zeros. Storing these as standard 2D arrays is memory-inefficient. Implement a class SparseMatrix that stores only the non-zero elements and supports addition and multiplication.
Requirements
__init__(self, rows, cols): Initialize an empty matrix of sizerows x cols.set(self, r, c, val): Set the value at(r, c)toval.get(self, r, c): Return the value at(r, c).add(self, other): Return a newSparseMatrixthat is the sum ofselfandother.multiply(self, other): Return a newSparseMatrixthat is the product ofselfandother.
Constraints
- Use a data structure that consumes O(N) space, where N is the number of non-zero elements.
- Assume
rowsandcolscan be up to 10,000, but N remains manageable (e.g., < 100,000).
Example
# Matrix A: 2x2
# [1, 0]
# [0, 2]
A = SparseMatrix(2, 2)
A.set(0, 0, 1)
A.set(1, 1, 2)
# Addition: A + A
B = A.add(A)
# Result: [[2, 0], [0, 4]]
Hints
Hint 1
Consider using a dictionary or a hash map where the key is the tuple (row, col) and the value is the element to represent non-zero entries.
Hint 2
For addition, iterate through the keys of both matrices and sum values where keys overlap; for multiplication, consider using the Compressed Sparse Row (CSR) format or iterating over columns of the second matrix.
Hint 3
To optimize multiplication, pre-group elements of the second matrix by their row indices to avoid searching for non-zero entries in every iteration.
Follow-up questions
- How does your implementation change if the matrices are extremely large and stored on disk?
- What is the time complexity of your multiplication operation in terms of non-zero elements?
- How would you handle potential memory issues if the matrix is 'dense-sparse' (i.e., the number of non-zero elements approaches rows * cols)?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.