#2718
Medium Algorithms Sum of matrix after queries
Array Hash Table
31.9% acceptance
Feb 25, 2026
732
27
You are given an integer n and a 0-indexed 2D array queries where queries[i] = [typei, indexi, vali].
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 typei == 0, set the values in the row with indexi to vali, overwriting any previous values.
if typei == 1, set the values in the column with indexi to vali, overwriting any previous values.
Return the sum of integers in the matrix after all queries are applied.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn matrix_sum_queries(n: i32, queries: Vec<Vec<i32>>) -> i64 {
let n = n as usize;
let mut row_set = vec![false; n];
let mut col_set = vec![false; n];
let mut unset_rows = n;
let mut unset_cols = n;
let mut sum = 0i64;
for q in queries.iter().rev() {
let (t, idx, val) = (q[0] as usize, q[1] as usize, q[2] as i64);
if t == 0 {
if !row_set[idx] {
row_set[idx] = true;
sum += val * unset_cols as i64;
unset_rows -= 1;
}
} else if !col_set[idx] {
col_set[idx] = true;
sum += val * unset_rows as i64;
unset_cols -= 1;
}
}
sum
}
}