1. Direct 2D Iteration (Brute Force)
Intuition
Given rectangle bounds (row1, col1) to (row2, col2), execute two nested loops summing matrix[r][c] for row1 <= r <= row2 and col1 <= c <= col2. Each query takes O((row2 - row1 + 1) * (col2 - col1 + 1)).
When to apply: Use for one-off single queries when matrix memory cannot be allocated for preprocessing.
Nested Matrix Cells Iteration (O(R * C) per Query)
2 of 2 questions left todayDirectly reading cell (1, 1)
Directly reading cell (1, 1).
public class Main { public static class NumMatrix { private int[][] mat; public NumMatrix(int[][] matrix) { this.mat = matrix; } public 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 += mat[r][c]; } } return sum; } } public static void main(String[] args) { int[][] matrix = { {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} }; NumMatrix nm = new NumMatrix(matrix); System.out.println("Region Sum: " + nm.sumRegion(2, 1, 4, 3)); }}Time & Space Complexity
- Time complexity:
O(1) init, O(R * C) per query— No precomputation; each query iterates through the queried rectangle of size R * C. - Space complexity:
O(1)— Only constant extra accumulator variables.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.