Implement sparse matrix addition and multiplication
VoleonSoftware Engineer · Technical ScreenLast updated
This question evaluates implementation skills for sparse matrix addition and multiplication, focusing on data structure selection, algorithmic complexity, memory efficiency, and explicit error handling within the Coding & Algorithms domain and the linear algebra/data-structures crossover.
Implement sparse-matrix operations with explicit error handling.
Sparse matrix
A matrix A has dimensions r x c and is sparse, meaning most entries are zero.
You may choose a representation (e.g., hashmap/dictionary keyed by (row, col) for non-zero values, or compressed rows), but your implementation should be efficient for sparse inputs.
Tasks
Implement:
add(A, B)→ returnsA + Bmul(A, B)→ returnsA * B
Requirements
- If dimensions are incompatible:
- For addition:
AandBmust have the same shape. - For multiplication:
Aisr x k,Bmust bek x c. - Incompatible dimensions must trigger clear error handling (e.g., raise an exception or return an error value, as specified by your interface).
- Preserve sparsity: avoid iterating over all
r*ccells.
Input/Output (one reasonable interface)
- Input: two sparse matrices
- Output: a sparse matrix (or error)
Constraints (reasonable interview constraints)
- Up to
10^5non-zero entries per matrix. - Dimensions can be large (e.g., up to
10^9), so dense storage is not allowed.
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.