Design a Compressed Sparse Row Matrix With Matvec and Transpose
Last updated: November 29, 2026
Quick Overview
Design a sparse matrix class stored in compressed sparse row form that is built from (row, col, value) triplets with duplicates summed, and supports element lookup, matrix-vector multiply, and transpose.
MathWorks
November 29, 20260
0
0 solved
Design a sparse matrix class stored in compressed sparse row form that is built from (row, col, value) triplets with duplicates summed, and supports element lookup, matrix-vector multiply, and transpose.
MATLAB's sparse() function and its solvers depend on compact sparse storage, so a MathWorks onsite may ask you to design one. The interviewer checks that you understand the row pointer, column index and value arrays, keep columns sorted per row for binary search, and match MATLAB semantics such as summing duplicate triplets.
What the Interviewer Expects
- Explains the three CSR arrays and what row_ptr[r]..row_ptr[r+1] means
- Sums duplicate triplets and drops explicit zeros, as MATLAB's sparse does
- Implements get with binary search inside a row
- Implements matvec in O(nnz) and transpose by rebuilding
- Compares CSR with CSC (MATLAB's internal choice) and coordinate format
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- MATLAB stores sparse matrices column-major (CSC). Which operations get faster or slower compared with your CSR design?
- How would you support inserting a new nonzero efficiently, given that CSR insertion is O(nnz)?
- How would you multiply two CSR matrices without materializing a dense intermediate?
- How would you parallelize matvec across threads?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Constructor: CSRMatrix(n_rows, n_cols, triplets). Duplicates at the same position add up; entries that sum to zero are not stored. get(r, c) returns the value or 0. matvec(x) returns A*x. `tra...
High-Level Design
Accumulate triplets into a dict, sort by (row, col), then fill col_idx and values in that order. Count entries per row into row_ptr[r+1] and prefix-sum so row r lives at `[row_ptr[r], row_ptr[...