1. Nested Iteration over Submatrix
Intuition
Maintain the matrix as a 2D array.
- update(row, col, val): Directly set matrix[row][col] = val in O(1) time.
- sumRegion(row1, col1, row2, col2): Use two nested loops iterating from row1 to row2 and col1 to col2, accumulating the sum in O((row2 - row1 + 1) \cdot (col2 - col1 + 1)) = O(m \cdot n) time.
For 10,000 operations on a 200 × 200 matrix, this approach takes up to 4 × 108 operations, risking TLE.
When to apply: Basic prototyping when matrix dimensions or queries are very small.
Algorithm
- Step 1: Store 2D array matrix.
- Step 2: On update(row, col, val), matrix[row][col] = val in O(1).
- Step 3: On sumRegion(r1, c1, r2, c2), nested loop r from r1 to r2 and c from c1 to c2 summing matrix[r][c].
- Step 4: Return sum.
#include <iostream>#include <vector> class NumMatrixBrute { std::vector<std::vector<int>> matrix;public: NumMatrixBrute(std::vector<std::vector<int>>& mat) : matrix(mat) {} void update(int row, int col, int val) { matrix[row][col] = val; } int sumRegion(int row1, int col1, int row2, int col2) { int sum = 0; for (int r = row1; r <= row2; ++r) { for (int c = col1; c <= col2; ++c) { sum += matrix[r][c]; } } return sum; }}; int main() { std::vector<std::vector<int>> mat = { {3, 0, 1, 4, 2}, {5, 6, 3, 2, 1}, {1, 2, 0, 1, 5}, {4, 1, 0, 1, 7}, {1, 0, 3, 0, 5} }; NumMatrixBrute nm(mat); std::cout << nm.sumRegion(2, 1, 4, 3) << std::endl; nm.update(3, 2, 2); std::cout << nm.sumRegion(2, 1, 4, 3) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(1) for update, O(m * n) for sumRegion - Space complexity:
O(m * n) auxiliary space