Sum of Matrix After Queries - Problem
Matrix Query Operations: You're given an
Each query has three parts:
• If
• If
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.
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 valueGoal: 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],[1,1,2],[1,1,2]]. Query [0,0,3] sets row 0 to [3,3,3], final matrix: [[3,3,3],[1,1,2],[1,1,2]]. Sum = 3+3+3+1+1+2+1+1+2 = 17. Wait, let me recalculate: [[3,3,2],[1,1,2],[1,1,2]] since column operation happened before final row operation. Sum = 3+3+2+1+1+2+1+1+2 = 16. Actually, the intersection cell (0,2) gets the final row value 3. So final matrix is [[3,3,3],[1,1,2],[1,1,2]] and sum is 17.
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
Understanding the Visualization
1
Start from Final State
Begin with the last command - it definitely affects the final result
2
Work Backwards
For each earlier command, check if it affects areas not yet processed
3
Calculate Impact
Count how many cells each command actually influences in the final state
4
Sum Contributions
Add up all the effective contributions without building the full matrix
Key Takeaway
🎯 Key Insight: Process queries in reverse order - only the last operation affecting each cell matters, allowing us to calculate the sum without building the entire matrix!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code