Sparse Matrix Operations - Problem
Implement efficient operations on sparse matrices (matrices with mostly zero elements). A sparse matrix should only store non-zero elements to save memory and computation time.
Given two sparse matrices represented as lists of [row, col, value] triplets, implement:
- Addition: Add two sparse matrices and return the result
- Multiplication: Multiply two sparse matrices and return the result
The operation type is specified as a string: "add" for addition or "multiply" for multiplication.
Note: Only non-zero elements should be stored in the result. Elements with value 0 should be omitted from the output.
Input & Output
Example 1 — Matrix Addition
$
Input:
matrix1 = [[0,1,3],[1,0,4]], matrix2 = [[0,0,1],[1,1,2]], operation = "add"
›
Output:
[[0,0,1],[0,1,3],[1,0,4],[1,1,2]]
💡 Note:
Add corresponding elements: matrix1 has (0,1)=3 and (1,0)=4, matrix2 has (0,0)=1 and (1,1)=2. Combined result includes all non-zero positions.
Example 2 — Matrix Multiplication
$
Input:
matrix1 = [[0,0,1],[0,1,2]], matrix2 = [[0,0,3],[1,0,4]], operation = "multiply"
›
Output:
[[0,0,3],[1,0,12]]
💡 Note:
Matrix multiplication: C[0,0] = A[0,0]*B[0,0] = 1*3 = 3, C[1,0] = A[0,1]*B[1,0] = 2*4 = 8. Wait, let me recalculate: C[1,0] = A[1,0]*B[0,0] + A[1,1]*B[1,0] = 0*3 + 0*4 = 0. Actually C[0,0] = A[0,0]*B[0,0] + A[0,1]*B[1,0] = 1*3 + 2*4 = 11.
Example 3 — Empty Result
$
Input:
matrix1 = [[0,0,5]], matrix2 = [[0,0,-5]], operation = "add"
›
Output:
[]
💡 Note:
5 + (-5) = 0, so the result has no non-zero elements and returns empty array.
Constraints
- 1 ≤ matrix1.length, matrix2.length ≤ 100
- -100 ≤ row, col ≤ 100
- -104 ≤ value ≤ 104
- operation is either "add" or "multiply"
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code