Leetcode 2718: Sum of Matrix After Queries

grid47
grid47
Exploring patterns and algorithms
Feb 9, 2024 6 min read

You are given a number n and a list of queries. Initially, an n x n matrix is filled with zeros. Each query updates either a row or a column in the matrix to a given value. After applying all the queries, compute and return the sum of all elements in the matrix.
Problem
Approach
Steps
Complexity
Input: A number n and a list of queries, where each query is of the form [typei, indexi, vali].
Example: n = 3, queries = [[0, 0, 1], [1, 2, 2], [0, 2, 3], [1, 0, 4]]
Constraints:
• 1 <= n <= 10^4
• 1 <= queries.length <= 5 * 10^4
• queries[i].length == 3
• 0 <= typei <= 1
• 0 <= indexi < n
• 0 <= vali <= 10^5
Output: Return the sum of all elements in the matrix after all queries are applied.
Example: 23
Constraints:
• The sum will be a non-negative integer.
Goal: The goal is to efficiently calculate the sum of the matrix after applying all queries.
Steps:
• Keep track of the changes for each row and column separately.
• Process the queries in reverse order to minimize redundant updates.
• Update the matrix based on the query type (row or column) and compute the sum.
Goal: The input constraints ensure the solution must handle large matrices efficiently.
Steps:
• 1 <= n <= 10^4
• 1 <= queries.length <= 5 * 10^4
• 0 <= vali <= 10^5
Assumptions:
• The matrix is initially filled with zeros.
Input: Example 1
Explanation: For n = 3 and queries = [[0, 0, 1], [1, 2, 2], [0, 2, 3], [1, 0, 4]], we update the matrix according to the queries and calculate the sum of all elements.

Input: Example 2
Explanation: For n = 3 and queries = [[0, 0, 4], [0, 1, 2], [1, 0, 1], [0, 2, 3], [1, 2, 1]], the sum of all matrix elements after applying the queries is 17.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus