#2718
Sum of Matrix After Queries
MediumArrayHash TableHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of maintaining the entire matrix, we can track the last update for each row and column. This allows us to compute the final sum efficiently without explicitly constructing the matrix.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two arrays to track the last value set for each row and column, and their respective types.
- 2Step 2: Process the queries in reverse order to determine the last effective update for each row and column.
- 3Step 3: Calculate the total sum by considering the last updates for each row and column, ensuring to avoid double counting.
solution.py20 lines
1def sumMatrixAfterQueries(n, queries):
2 row_values = [0] * n
3 col_values = [0] * n
4 row_last_update = [-1] * n
5 col_last_update = [-1] * n
6 for i in range(len(queries) - 1, -1, -1):
7 type_i, index_i, val_i = queries[i]
8 if type_i == 0:
9 row_values[index_i] = val_i
10 row_last_update[index_i] = i
11 else:
12 col_values[index_i] = val_i
13 col_last_update[index_i] = i
14 total_sum = 0
15 for i in range(n):
16 if row_last_update[i] > col_last_update[i]:
17 total_sum += row_values[i] * n
18 else:
19 total_sum += col_values[i] * n
20 return total_sumℹ
Complexity note: The time complexity is O(n) because we only traverse the queries once and then compute the sum based on the last updates, which is linear with respect to n.
- 1Processing queries in reverse helps identify the last effective update for each row and column.
- 2Using arrays to track the last values and their types avoids unnecessary matrix construction.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.