Sum of Matrix After Queries

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def matrixSumQueries(self, n: int, queries: List[List[int]]) -> int:
        res = 0
        cols_cnt = n
        rows_cnt = n
        cols = [False] * n
        rows = [False] * n
        for i in range(len(queries) - 1, -1, -1):
            type_i, id, v = queries[i]
            if type_i == 0:  # row
                if not rows[id]:
                    rows[id] = True
                    rows_cnt -= 1
                    res += v * cols_cnt
            else:  # col
                if not cols[id]:
                    cols[id] = True
                    cols_cnt -= 1
                    res += v * rows_cnt
        return res

10 Prerequisite LeetCode Problems

For “2718. Sum of Matrix After Queries”, the following is a good preparation:

  1. “370. Range Addition” - This problem also deals with applying operations to a range of elements in an array. Understanding the effects of these operations on the cumulative sum can be beneficial.

  2. “1381. Design a Stack With Increment Operation” - This problem involves a stack with an additional increment operation that affects a range of elements, helping you understand how to handle range updates.

  3. “1572. Matrix Diagonal Sum” - This problem asks you to find the sum of elements in a matrix, a concept that is useful for the target problem.

  4. “1672. Richest Customer Wealth” - This problem requires finding the maximum sum among all rows of a matrix, providing practice with operations on matrix rows.

  5. “1576. Replace All ?’s to Avoid Consecutive Repeating Characters” - This problem involves modifying an array according to some conditions, similar to how you modify a matrix in the target problem.

  6. “598. Range Addition II” - This problem involves applying an increment operation over a range in a matrix, which is a similar concept to the target problem.

  7. “1089. Duplicate Zeros” - This problem involves modifying an array by replacing certain values, providing practice for similar operations in the target problem.

  8. “1299. Replace Elements with Greatest Element on Right Side” - This problem involves replacing elements in an array based on conditions related to other elements, a concept that is useful for the target problem.

  9. “1582. Special Positions in a Binary Matrix” - This problem involves operations and conditions on matrix rows and columns, providing relevant practice for the target problem.

  10. “1464. Maximum Product of Two Elements in an Array” - This problem involves finding the maximum product of two elements in an array. Understanding how to approach maximum/minimum problems can be beneficial for understanding how to approach sum problems.

These involve operations and conditions on arrays or matrices, sum calculations, and range updates, which are useful concepts for the target problem.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def matrixSumQueries(self, n: int, queries: List[List[int]]) -> int:
        rowSeenCount, colSeenCount, total = 0, 0, 0
        rowSeen, colSeen = [False] * n, [False] * n
        for qi in range(len(queries) - 1, -1, -1):
            typei, index, val = queries[qi][0], queries[qi][1], queries[qi][2]
            if typei == 0 and not rowSeen[index]:
                rowSeenCount += 1
                rowSeen[index] = True
                total += (n - colSeenCount) * val
            if typei == 1 and not colSeen[index]:
                colSeenCount += 1
                colSeen[index] = True
                total += (n - rowSeenCount) * val
        return total

Problem

Problem Statement: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.

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 <= 104 1 <= queries.length <= 5 * 104 queries[i].length == 3 0 <= typei <= 1 0 <= indexi < n 0 <= vali <= 105

Analyze the provided problem statement. Categorize it based on its domain, ignoring ‘How’ it might be solved. Identify and list out the ‘What’ components. Based on these, further classify the problem. Explain your categorizations.

Problem Classification

Domain Categorization:

This problem is based in the domain of “Computer Science - Data Structures”. Specifically, it involves operations on 2D arrays or matrices.

‘What’ Components:

  1. An integer ’n’ - represents the dimension of the square matrix.
  2. A 2D array ‘queries’ - represents a list of instructions to modify the matrix.
  3. An operation based on ’type’ - represents the operation to be performed on the matrix (modifying a row or column).
  4. An ‘index’ - represents the row or column to be modified.
  5. A ‘val’ - represents the value to be used to modify the row or column in the matrix.
  6. A matrix - represents the 2D data structure on which the operations are to be performed.
  7. A final matrix sum - represents the sum of all elements in the matrix after all queries have been applied.

Problem Classification:

This problem can be classified as a “Simulation” type problem because it involves simulating the operation of applying a sequence of operations (the queries) to a data structure (the matrix) and observing the result (the final sum of matrix elements).

Explanation:

The problem involves creating a data structure (a matrix), performing a sequence of operations on it (the queries), and obtaining a final result (the sum of the matrix elements). The operations to be performed involve two types of modifications to the matrix, modifying a row or modifying a column, and these modifications involve writing a specific value to the row or column. The final result is the sum of all the matrix elements after all the queries have been applied. The problem is to simulate this sequence of operations and compute the final result.

Language Agnostic Coding Drills

  1. Coding Concepts:

    a. Variable Initialization: Involves creating variables and setting their initial values. This is seen with the initialization of rowSeenCount, colSeenCount, total, rowSeen, and colSeen.

    b. Iterating through a List: This is done using a for-loop, iterating from the end of the list to the start in this case.

    c. Array Indexing: Accessing elements of an array based on their indices. This is seen in accessing the query queries[qi].

    d. Conditional Statements (if-statements): Used to perform operations based on certain conditions. For instance, the conditions check whether a row or a column has been modified.

    e. Updating Variables: Based on conditions, variables are updated. This includes rowSeenCount, colSeenCount, rowSeen, colSeen, and total.

  2. Difficulty Classification:

    a. Variable Initialization: Easy. It is a fundamental concept in any programming language.

    b. Iterating through a List: Easy. It’s also a fundamental concept but slightly more complex than variable initialization.

    c. Array Indexing: Easy to Medium. It involves understanding how to access data in a structured form, and some knowledge of how data is organized is needed.

    d. Conditional Statements (if-statements): Medium. It requires understanding of logical expressions and control flow.

    e. Updating Variables: Medium. It needs comprehension of existing variable states and conditions in order to make correct updates.

  3. Problem-solving Approach:

    This code adopts an optimization strategy to the problem. Rather than actually creating and modifying a matrix, it keeps track of rows and columns that have been seen (modified) and calculates the total sum on the fly.

    The process starts by initializing tracking variables and counters. Then it iterates over the queries in reverse order. For each query, it checks the type of operation and whether the row or column has been seen before. If the row or column has not been seen, it updates the counters and calculates the added value for the total sum, considering the number of unseen rows or columns (since a seen row or column would have been overwritten by a previous operation). The tracking lists for rows and columns are updated so that each row or column is only counted once.

    The use of the tracking variables (rowSeen, colSeen, rowSeenCount, and colSeenCount) enables this optimization by avoiding the need for an actual matrix and preventing overcounting of rows and columns that are modified more than once. The total sum is then returned at the end.

Targeted Drills in Python

  1. Python Drills for Each Concept:

    a. Variable Initialization:

    1
    2
    3
    
    count = 0
    flag = False
    my_list = [1, 2, 3, 4, 5]
    

    b. Iterating through a List:

    1
    2
    
    for i in range(len(my_list)):
        print(my_list[i])
    

    c. Array Indexing:

    1
    
    print(my_list[2])  # Accesses the third element of the list.
    

    d. Conditional Statements (if-statements):

    1
    2
    3
    4
    
    if count > 2:
        print("Count is greater than 2")
    else:
        print("Count is less than or equal to 2")
    

    e. Updating Variables:

    1
    2
    
    count += 1  # Increases the count by one.
    flag = not flag  # Flips the boolean value of flag.
    
  2. Drills for Specific Needs of the Problem:

    a. Iterating in Reverse Order:

    1
    2
    
    for i in range(len(my_list)-1, -1, -1):
        print(my_list[i])
    

    b. Checking and Updating a Flag:

    1
    2
    
    if not flag:
        flag = True
    

    c. Modifying List Values:

    1
    
    my_list[2] = 10  # Changes the third element of the list to 10.
    
  3. Merging the Drills:

    Begin by initializing your tracking variables and arrays. After this, set up your loop to iterate over the queries in reverse order. Inside the loop, extract the elements of each query and check the type of operation. If the operation is for a row and the row has not been seen before, mark it as seen and update the total sum. Do the same for column operations. Return the total sum at the end. These drills come together to form the final solution, which cleverly avoids the need for a matrix by tracking changes to rows and columns directly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def matrixSumQueries(self, n: int, queries: List[List[int]]) -> int:
        rowSeenCount, colSeenCount, total = 0, 0, 0
        rowSeen, colSeen = [False] * n, [False] * n
        for qi in range(len(queries) - 1, -1, -1):
            typei, index, val = queries[qi][0], queries[qi][1], queries[qi][2]
            if typei == 0 and not rowSeen[index]:
                rowSeenCount += 1
                rowSeen[index] = True
                total += (n - colSeenCount) * val
            if typei == 1 and not colSeen[index]:
                colSeenCount += 1
                colSeen[index] = True
                total += (n - rowSeenCount) * val
        return total

Problem Classification

Language Agnostic Coding Drills

  1. Basic data types and operations: Understand how to declare and perform basic operations on integers.

  2. Lists: Understand how to declare lists, access their elements, and modify them.

  3. Loops: Learn how to use loops to iterate over the list of queries. Specifically, the concept of a reverse loop (range(len(queries) - 1, -1, -1)) needs to be understood.

  4. Conditionals: Understanding the use of if statements for conditional execution of code.

  5. Indexing: Understanding how to index into a list of lists (queries[qi][0], queries[qi][1], queries[qi][2]).

  6. Boolean Variables and Operations: Understand how to declare and manipulate boolean variables. This includes the use of boolean variables as flags (rowSeen[index] = True).

  7. Arithmetic operations: Learn the use of arithmetic operations for calculating the total. Note the use of multiplication and addition operations.

  8. Object-Oriented Programming (Classes and Methods): Understanding how to create classes and methods in a class.

Here’s a progression of drills in increasing difficulty that can be followed:

  1. Declare, initialize and manipulate integer variables.
  2. Declare, initialize and manipulate lists.
  3. Write for loops to iterate over lists.
  4. Use conditional statements to execute code based on certain conditions.
  5. Write a for loop in reverse order.
  6. Index into a list of lists.
  7. Declare, initialize, and manipulate boolean variables.
  8. Write complex arithmetic expressions involving multiple operations.
  9. Write a basic class with a single method.
  10. Write a class that uses all of the above concepts.

Targeted Drills in Python

  1. Declare, initialize and manipulate integer variables.
1
2
3
4
x = 10
y = 20
z = x + y
print(z)
  1. Declare, initialize and manipulate lists.
1
2
3
4
l = [1, 2, 3, 4, 5]
l[0] = 10
l.append(6)
print(l)
  1. Write for loops to iterate over lists.
1
2
3
l = [1, 2, 3, 4, 5]
for i in l:
    print(i)
  1. Use conditional statements to execute code based on certain conditions.
1
2
3
4
5
x = 10
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")
  1. Write a for loop in reverse order.
1
2
for i in range(10, -1, -1):
    print(i)
  1. Index into a list of lists.
1
2
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(l[1][2])
  1. Declare, initialize, and manipulate boolean variables.
1
2
3
4
5
6
flag = True
if flag:
    print("Flag is True")
else:
    print("Flag is False")
flag = False
  1. Write complex arithmetic expressions involving multiple operations.
1
2
3
4
x = 10
y = 20
z = (x+y)*2 - (x/y)
print(z)
  1. Write a basic class with a single method.
1
2
3
4
5
6
class MyClass:
    def my_method(self):
        print("This is a method inside MyClass")

obj = MyClass()
obj.my_method()
  1. Write a class that uses all of the above concepts.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def arithmetic_operations(self, x: int, y: int) -> int:
        if x > y:
            return x - y
        else:
            return x + y

    def manipulate_lists(self, l: List[int]) -> List[int]:
        for i in range(len(l)):
            l[i] += self.arithmetic_operations(i, l[i])
        return l

s = Solution()
print(s.manipulate_lists([1, 2, 3, 4, 5]))