Escape the Matrix
Implement SparseMatrix, which represents a matrix that stores only non-zero values and supports efficient matrix operations.
This problem focuses on data structure design and algorithmic efficiency, not linear algebra tricks.
Constructor
SparseMatrix(rows, cols)
rowsis the number of rows in the matrix.colsis the number of columns in the matrix.- The matrix is initially all zeros.
- Zero values must not be stored internally.
Methods
set(r, c, val)
- Sets the value at position
(r, c)toval. - If
val == 0, the entry must be removed from storage if present. - You may assume
0 ≤ r < rowsand0 ≤ c < cols.
get(r, c)
- Returns the value at position
(r, c). - If the entry is not present, return
0.
add(other)
- Returns a new
SparseMatrixequal tothis + other. - Matrix dimensions must match.
- Only non-zero entries should be stored in the result.
multiply(other)
- Returns a new
SparseMatrixequal tothis * other. - Requires
this.cols == other.rows. - The implementation must avoid iterating over zero entries.
nnz()
- Returns the number of non-zero entries currently stored in the matrix.
Behavior Details
- All operations must preserve sparsity (no dense conversion allowed).
- Multiple operations may be chained.
- Addition and multiplication must only process entries that actually exist.
- The implementation should be efficient for large dimensions with few non-zero values.
Input Format
The first line contains an integer Q, the number of operations.
Each of the next Q lines is one of the following:
NEW name rows cols
Create a new sparse matrix with the given name.SET name r c val
Callset(r, c, val)on matrixname.GET name r c
Callget(r, c)and output the result.ADD out A B
ComputeA + Band store the result inout.MUL out A B
ComputeA * Band store the result inout.NNZ name
Callnnz()and output the result.
You may assume:
- Matrix names are unique unless overwritten by an operation.
- All indices are valid.
- Errors should be reported if dimensions are incompatible.
Output Format
- For each
GEToperation, output a single integer. - For each
NNZoperation, output a single integer. - For invalid
ADDorMULoperations, outputERROR.
Notes
- You may not convert the matrix to a dense representation.
- A correct solution should run in time proportional to the number of non-zero entries involved.
- This problem is about implementation and data structures, not numerical precision.
Constraints
1 ≤ rows, cols ≤ 200000- Total number of non-zero entries across all matrices ≤
2 * 10^5 - Values fit in 32-bit signed integers
Examples
Example 1
Input:
11
NEW A 3 4
NEW B 3 4
SET A 0 1 5
SET A 2 3 7
SET B 0 1 -2
SET B 1 0 4
ADD C A B
GET C 0 1
GET C 1 0
NNZ C
MUL D A BOutput:
3
4
3
ERRORAccepted 1/1
Acceptance 100%
Loading editor...
Sample Input:
11
NEW A 3 4
NEW B 3 4
SET A 0 1 5
SET A 2 3 7
SET B 0 1 -2
SET B 1 0 4
ADD C A B
GET C 0 1
GET C 1 0
NNZ C
MUL D A BExpected Output:
3
4
3
ERROR