C++||Solutions🚀||Explained Line by Line ✔✔||Easy to understand😊||Beginner Friendly🚀✔✔
Intuition\n Describe your first thoughts on how to solve this problem. \nThe code works based on the intuition that for each query, it checks if a row or column
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code works based on the intuition that for each query, it checks if a row or column index has been visited before. If it hasn\'t, it adds the product of the remaining row or column count and the value to the sum. This ensures that the sum considers only the elements that have not been previously accounted for in the visited rows or columns.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe code uses two sets, r and c, to store the row and column indices encountered in the queries.\n\nThe queries are reversed to iterate over them in reverse order.\n\nA variable ans is initialized to store the sum of matrix elements.\n\nThe code iterates over each query, performs row or column operations, and updates the sum accordingly.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the code is O(q), where q is the number of queries. Since the code iterates over the queries in reverse order, it performs constant time operations for each query. Therefore, the time complexity is linear with respect to the number of queries.\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of the code is O(n), where n is the size of the matrix. This is because the code uses two sets, r and c, to store visited row and column indices. The size of these sets can grow at most up to the number of rows or columns in the matrix.\n\n# Code\n```\nclass Solution {\npublic:\n   long long matrixSumQueries(int n, vector<vector<int>>& queries) {\n    set<int> r, c; // Create two sets to store the row and column indices\n    reverse(queries.begin(), queries.end()); // Reverse the order of queries\n    long long ans = 0; // Initialize a variable to store the sum of matrix elements\n    for(auto it : queries) {\n        if(it[0] == 0) { // Query type 0: row operation\n            if(r.find(it[1]) == r.end()) { // If the row index is not present in the set\n                ans += (n - c.size()) * it[2]; // Add the product of (remaining column count) and the value to the answer\n                r.insert(it[1]); // Insert the row index into the set\n            }\n        }\n        else { // Query type 1: column operation\n            if(c.find(it[1]) == c.end()) { // If the column index is not present in the set\n                ans += (n - r.size()) * it[2]; // Add the product of (remaining row count) and the value to the answer\n                c.insert(it[1]); // Insert the column index into the set\n            }\n        }\n    }\n    return ans; // Return the final sum of matrix elements\n}\n\n};\n```
['C++']