Sum of Matrix After Queries Problem
#2718
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2718.
You are given an integer n and a 0-indexed 2D array queries where queries[i] = [type_i, index_i, val_i].
Initially, there is a 0-indexed n x n matrix filled with 0's. For each query, you must apply one of the following changes:
- if
type_i == 0, set the values in the row withindex_itoval_i, overwriting any previous values. - if
type_i == 1, set the values in the column withindex_itoval_i, overwriting any previous values.
Return the sum of integers in the matrix after all queries are applied.
Example 1:

Input: n = 3, queries = [[0,0,1],[1,2,2],[0,2,3],[1,0,4]]
Output: 23
Explanation: The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 23.
Example 2:

Input: n = 3, queries = [[0,0,4],[0,1,2],[1,0,1],[0,2,3],[1,2,1]]
Output: 17
Explanation: The image above describes the matrix after each query. The sum of the matrix after all queries are applied is 17.
Constraints:
1 <= n <= 10^41 <= queries.length <= 5 * 10^4queries[i].length == 30 <= type_i <= 10 <= index_i < n0 <= val_i <= 10^5
Solution
Approach: Process Queries in Reverse
A cell ends up with the value of the last query that touched its row or its column. So walk through the queries from last to first, remembering which rows and which columns have already been claimed by a later query.
For a query (t, i, v):
- If it is a row query (
t = 0) and rowiis not claimed yet, this query decides every cell of that row whose column is not claimed yet. That isn - |col|cells, so addv * (n - |col|)and mark the row as claimed. - If it is a column query (
t = 1) and columniis not claimed yet, addv * (n - |row|)and mark the column. - Otherwise a later query already overwrote this line, so skip it.
Complexity: O(m) time for m queries and O(n) extra space.
class Solution:
def matrixSumQueries(self, n: int, queries: List[List[int]]) -> int:
row = set()
col = set()
ans = 0
for t, i, v in queries[::-1]:
if t == 0:
if i not in row:
ans += v * (n - len(col))
row.add(i)
else:
if i not in col:
ans += v * (n - len(row))
col.add(i)
return ans