[ INFO ]category: Coding difficulty: medium freq: high first seen: 2026-01-13
[MEDIUM][CODING][HIGH]DesignHash TableMatrix
$catproblem.md
Design and implement a SparseMatrix class that supports efficient storage and operations on matrices that are mostly zero. Your class must provide the following functionality:
Initialization with a given number of rows and columns.
set(row, col, val) – set the element at (row, col) to val. If val is zero, the element should be removed from internal storage.
get(row, col) – return the value at (row, col); return 0 if the element is not explicitly stored.
add(other) – return a new SparseMatrix that is the element-wise sum of this matrix and another SparseMatrix of the same dimensions.
multiply(other) – return a new SparseMatrix that is the matrix product of this matrix (left) and another SparseMatrix (right). The product should only compute terms where both factors are non-zero.
You must use a dictionary/hash-map based representation that stores only non-zero values keyed by (row, col) tuples. All operations must run in time proportional to the number of non-zero elements involved, not the full matrix dimensions. Handle edge cases such as empty matrices, setting a value to zero, and result entries that sum to zero.