line by line comments || easy to understand || beats 100%
Intuition\n Describe your first thoughts on how to solve this problem. \nFirstly, we consider the simulation approach. We iterate form the first query to the la
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirstly, we consider the simulation approach. We iterate form the first query to the last query, and set value for each cell. Then we traverse the matrix, ans get the final sum. But the simulation approach\'s time complexity is too high. We handle a cell too many times. After thinking for a while, we realized that we only need to handle the last value of one cell, although it\'s not easy to think of that.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe key point to solve this problem is only handle the last value of one cell. So we iterate from the last query to the first query. Whenever we added a row of values or a column of values to the result, we marked that row or column deleted, because all previously setted values are overrided. There is no need to handle these values.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(queries.length)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\n    public long matrixSumQueries(int n, int[][] q) {\n        boolean[] row = new boolean[n]; // mark rows that are deleted. true meas deleted\n        boolean[] col = new boolean[n]; // mark columns that are deleted. true meas deleted\n        int rowRemain = n; // count the number of rows that are not deleted\n        int colRemain = n; // count the number of columns that are not deleted\n        long ans = 0;\n        for (int i = q.length - 1; i >= 0; --i) {\n            int type = q[i][0], index = q[i][1], value = q[i][2];\n            if (type == 0) {\n                if (!row[index]) { // the row has not been deleted\n                    // only not deleted columns contribute to the final sum\n                    ans += value * colRemain;\n                    row[index] = true; // mark this row is deleted\n                    --rowRemain; // decrease the number of not deleted rows\n                }\n            } else {\n                if (!col[index]) { // the column has not been deleted\n                    // only not deleted rows contribute to the final sum\n                    ans += value * rowRemain;\n                    col[index] = true; // mark this column is deleted\n                    --colRemain; // decrease the number of not deleted columns\n                }\n            }\n        }\n        return ans;\n    }\n}\n```
['Java']