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
INPUTSparse Matrix TripletsMatrix 1: [[0,1,3], [1,0,4]]Matrix 2: [[0,0,1], [1,1,2]]Dense would be 2×2:[0,3] + [1,0][4,0] [0,2]Operation: ADDALGORITHMHash Map Processing1Convert to MapsUse (row,col) as keys2Process PositionsAdd values at same keys3Combine ResultsUnion of all positionsHash Map Result:(0,0) → 1(0,1) → 3(1,0) → 4(1,1) → 2RESULTEfficient Sparse OutputFinal Triplets:[0,0,1][0,1,3][1,0,4][1,1,2]Efficiency Gain:Only 4 elements storedvs 4 elements in dense(In larger sparse matrices:100s vs 10,000s elements)Key Insight:Hash maps with position keys eliminate the need for dense matrix storage,processing only non-zero elements for massive memory and time savings in sparse data.TutorialsPoint - Sparse Matrix Operations | Hash Map Approach
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 10
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen