Step by step detailed explanation of short code🔥
Intuition\nThe problem involves performing sum queries on a matrix. We are given the size of the matrix n and a list of queries, where each query specifies whet
# Intuition\nThe problem involves performing sum queries on a matrix. We are given the size of the matrix n and a list of queries, where each query specifies whether to add a value to a row or column and the corresponding index. Our goal is to calculate the sum after applying all the queries.\n\n# Approach\n1. Initialize a variable sum to keep track of the sum and set it to 0.\n2. Create two sets, row and col, to store the indices of the rows and columns affected by the queries.\n3. Iterate over the queries in reverse order, starting from the last query. This allows us to process the queries in reverse order while still maintaining the correct sum.\n4. For each query, extract the type, index, and value.\n5. If the query type is 1 (column query), check if the column index ind is already present in the col set. If it is, continue to the next query.\n6. Add the column index ind to the col set.\n7. Update the sum by adding the product of the value val and the number of rows not affected by the column queries (n - row.size).\n8. If the query type is 0 (row query), check if the row index ind is already present in the row set. If it is, continue to the next query.\nAdd the row index ind to the row set.\n9. Update the sum by adding the product of the value val and the number of columns not affected by the row queries (n - col.size).\n10. After processing all the queries, return the final value of sum.\n# Complexity\n* Time complexity: O(k), where k is the number of queries. We iterate over the queries in reverse order, performing constant time operations for each query.\n* Space complexity: O(n), where n is the size of the matrix. We use two sets to store the indices of the affected rows and columns, which can have a maximum size of n.\n\n# Code\n```\nfunction matrixSumQueries(n: number, queries: number[][]): number {\n    let sum = 0 ;\n    let row = new Set() , col = new Set() , len = queries.length;\n    for( let i = len - 1 ; i >= 0 ; i-- ){\n        let [type , ind , val] = queries[i];\n        if(type){\n            if(col.has(ind))continue;\n            col.add(ind);\n            sum += (val * (n - row.size));\n        }\n        else {\n            if(row.has(ind))continue;\n            row.add(ind);\n            sum += (val * (n - col.size));\n        }\n    }\n    return sum;\n};\n```
['TypeScript', 'JavaScript']