Java / C++ 🔥 Easy to understand ⭐ (Faster than 100% ✈️) with set O(10^5) 📈
Intuition\nI tried n^2 approach but it was giving tle\n\n# Approach\nWe can declare two variables row and col which is the current length of row and col we then
# Intuition\nI tried n^2 approach but it was giving tle\n\n# Approach\nWe can declare two variables row and col which is the current length of row and col we then just take sum of the elements as we move forward.\n\n# Java Code \n(special thanks to @sai_prashant)\n```\nclass Solution {\n    public long matrixSumQueries(int n, int[][] queries) {\n        long row=n,col=n;\n        long sum=0;\n        HashSet<Integer> rowMap=new HashSet<>();\n        HashSet<Integer> colMap=new HashSet<>();\n        for(int i=queries.length-1;i>=0;i--){\n            if(queries[i][0]==0){\n                if(col<=0||rowMap.contains(queries[i][1]))continue;\n                sum+=(col)*(long)queries[i][2];\n                rowMap.add(queries[i][1]);\n                row--;\n            }else{\n                if(row<=0||colMap.contains(queries[i][1]))continue;\n                sum+=(row)*(long)queries[i][2];\n                colMap.add(queries[i][1]);\n                col--;\n            }\n        }\n        return sum;\n    }\n}\n```\n\n# C++ Code\n\n```\nclass Solution {\npublic:\n    \n    // so the logic is we start iterating queries array from the last\n    // we only update one row/col only once and then skip if they appear again\n    long long matrixSumQueries(int n, vector<vector<int>>& queries) {\n        int row = n,col = n;\n        long long ans = 0;\n        int x = queries.size();\n        unordered_set<int> rows,cols;\n        for(int i=(x-1);i>=0;i--){\n            if(col > 0 && queries[i][0] == 0){\n                if(rows.find(queries[i][1]) == rows.end()){\n                    ans += col * (long long) queries[i][2];\n                    row--;\n                    rows.insert(queries[i][1]);\n                }\n            }else if(row > 0){\n                if(cols.find(queries[i][1]) == cols.end()){\n                    ans += row * (long long) queries[i][2];\n                    col--;\n                    cols.insert(queries[i][1]);\n                }\n            }\n        }\n        return ans;\n    }\n};\n```
['Ordered Set', 'C++', 'Java']