✅ Javascript | Simplest Solution | 🏆HashSet🏆 |🔥Beats 100%🔥
\n\n# Intuition\nAvoid matrix manipulationsand, traverse through queries from the end with tacking visited cols and rows. Calculate sum as val * (n - cols / row
![image.png](https://assets.leetcode.com/users/images/b020c4d0-6955-43a4-9549-bc70774bf21d_1720800888.0060012.png)\n\n# Intuition\nAvoid matrix manipulationsand, traverse through `queries` from the end with tacking visited cols and rows. Calculate `sum` as `val * (n - cols / rows size)`, depending on current query.\n\n# Approach\nDefine:\n`n` - size of cols / rows;\n`sum` - result variable;\n`rows` - HashSet for tracking visited rows;\n`cols` - HashSet for tracking visited cols;\n\nTraverse through `queries` from the end (because only last record is needed if the same col / row overwriting more than once).\n\nIn case of current query `type` is `0`(row) and row wasn\'t overwrited, add current row index to `rows` and add to sum `val` powered `n` minus number of filled cols;\n\nIn case of current query `type` is `1`(col) and col wasn\'t overwrited, add current col index to `cols` and add to sum `val` powered by `n` minus number of filled rows;\n\n# Complexity\n- Time complexity:\n$$O(queries)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\n/**\n * @param {number} n\n * @param {number[][]} queries\n * @return {number}\n */\nvar matrixSumQueries = function(n, queries) {\n    let sum = 0;\n    const rows = new Set();\n    const cols = new Set();\n\n    for(let i = queries.length - 1; i >= 0; i--) {\n        const [type, index, val] = queries[i];\n\n        if (type === 0 && !rows.has(index)) {\n            rows.add(index);\n            sum += val * (n - cols.size);\n        } else if (type === 1 && !cols.has(index)) {\n            cols.add(index);\n            sum += val * (n - rows.size);\n        }\n    }\n\n    return sum;\n};\n```
['Hash Table', 'JavaScript']