Sum of Matrix After Queries - Problem
Matrix Query Operations: You're given an n × n matrix initially filled with zeros and a series of queries that modify entire rows or columns at once.

Each query has three parts: [type, index, value]
• If type = 0: Set all values in row index to value
• If type = 1: Set all values in column index to value

Goal: After processing all queries in order, return the sum of all elements in the matrix.

Key Challenge: Later queries can overwrite earlier ones, so the order matters! A column operation after a row operation will overwrite the intersection cell.

Input & Output

example_1.py — Basic Matrix Operations
$ Input: n = 3, queries = [[0,0,1],[1,2,2],[0,0,3]]
Output: 13
💡 Note: Initial 3×3 matrix of zeros. Query [0,0,1] sets row 0 to [1,1,1]. Query [1,2,2] sets column 2 to [2,2,2], creating matrix [[1,1,2],[0,0,2],[0,0,2]]. Query [0,0,3] sets row 0 to [3,3,3], final matrix: [[3,3,3],[0,0,2],[0,0,2]]. Sum = 3+3+3+0+0+2+0+0+2 = 13.
example_2.py — Single Operation
$ Input: n = 2, queries = [[1,0,5]]
Output: 10
💡 Note: Start with 2×2 matrix of zeros. Query [1,0,5] sets column 0 to value 5. Final matrix: [[5,0],[5,0]]. Sum = 5+0+5+0 = 10.
example_3.py — Overwriting Operations
$ Input: n = 2, queries = [[0,0,2],[0,0,3],[1,1,4]]
Output: 14
💡 Note: Initial 2×2 zeros. [0,0,2] sets row 0 to [2,2]. [0,0,3] overwrites row 0 to [3,3]. [1,1,4] sets column 1 to [4,4]. Final matrix: [[3,4],[3,4]]. Sum = 3+4+3+4 = 14.

Constraints

  • 1 ≤ n ≤ 104
  • 1 ≤ queries.length ≤ 5 × 104
  • queries[i].length == 3
  • 0 ≤ typei ≤ 1
  • 0 ≤ indexi < n
  • 0 ≤ vali ≤ 105

Visualization

Tap to expand
Sum of Matrix After Queries INPUT Initial 3x3 Matrix (all zeros) 0 0 0 0 0 0 0 0 0 Queries: [0, 0, 1] - Row 0 = 1 [1, 2, 2] - Col 2 = 2 [0, 0, 3] - Row 0 = 3 n = 3 Process in reverse order! ALGORITHM (Hash) 1 Process Reverse Track seen rows/cols 2 Query [0,0,3] Row 0 new: 3 x 3 = 9 3 Query [1,2,2] Col 2 new: 2 x 2 = 4 4 Query [0,0,1] Row 0 seen: skip! Hash Sets: seenRows {0} seenCols {2} Sum Calculation: Row 0: 3 x (3-1) = 6 Col 2: 2 x (3-1) = 4 FINAL RESULT Final Matrix State: 3 3 3 0 0 2 0 0 2 Row 0: 3+3+3 = 9 Col 2 (rows 1,2): 2+2 = 4 OUTPUT 13 OK - Verified Key Insight: Process queries in REVERSE order using hash sets to track which rows/cols are already set. For each row/col operation, only count cells that haven't been overwritten by later operations. Time: O(q) where q = number of queries. Space: O(n) for the hash sets. TutorialsPoint - Sum of Matrix After Queries | Hash Approach
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
37.2K Views
Medium Frequency
~25 min Avg. Time
1.5K 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