Problem Description
Given an n x n matrix initially filled with 0's and a list of queries where each query either sets all values in a specified row or column to a given value, return the sum of all elements in the matrix after performing all the queries.
Key Insights
- Direct simulation of each query is too slow due to large constraints (n up to 10^4 and queries up to 5 * 10^4).
- Instead of simulating each update on all cells, one can calculate contributions of each query by processing the queries in reverse order.
- Use boolean markers for rows and columns to check whether a row or column's value has been "finalized" by a later query.
- When processing a query, if the target row or column hasn’t been updated later, its contribution is determined by the number of columns or rows that are still not finalized.
- This reverse approach ensures that each cell is counted only once from the most recent query that updated it.
Space and Time Complexity
Time Complexity: O(Q), where Q is the number of queries
Space Complexity: O(n), for maintaining markers for n rows and n columns
Solution
The solution works by processing the queries from the last to the first. We maintain two boolean arrays (or sets) to track whether a particular row or column has already been updated by a query that is later in the operation sequence (when read in forward order).
For each query in reverse:
- If the query updates a row and that row is not already marked, then add (value * number of columns still not updated) to the total sum and mark the row.
- If the query updates a column and that column is not already marked, then add (value * number of rows still not updated) to the total sum and mark the column.
This method ensures that we only account for updates that are not subsequently overwritten.