#304
Range Sum Query 2D - Immutable
MediumArrayDesignMatrixPrefix SumPrefix SumDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(m * n) |
💡
Intuition
Time O(1)Space O(m * n)
By using a prefix sum matrix, we can preprocess the input matrix to allow for O(1) sum queries. This is like having a cheat sheet that tells you the sum of any rectangle in constant time.
⚙️
Algorithm
3 steps- 1Step 1: Create a prefix sum matrix where each cell (i, j) contains the sum of all elements from (0, 0) to (i, j).
- 2Step 2: For each query, use the prefix sum matrix to calculate the sum of the specified rectangle using the inclusion-exclusion principle.
- 3Step 3: Return the calculated sum.
solution.py12 lines
1class NumMatrix:
2 def __init__(self, matrix):
3 self.matrix = matrix
4 self.rows = len(matrix)
5 self.cols = len(matrix[0]) if self.rows > 0 else 0
6 self.prefix_sum = [[0] * (self.cols + 1) for _ in range(self.rows + 1)]
7 for i in range(1, self.rows + 1):
8 for j in range(1, self.cols + 1):
9 self.prefix_sum[i][j] = (self.matrix[i-1][j-1] + self.prefix_sum[i-1][j] + self.prefix_sum[i][j-1] - self.prefix_sum[i-1][j-1])
10
11 def sumRegion(self, row1, col1, row2, col2):
12 return (self.prefix_sum[row2 + 1][col2 + 1] - self.prefix_sum[row1][col2 + 1] - self.prefix_sum[row2 + 1][col1] + self.prefix_sum[row1][col1])ℹ
Complexity note: The time complexity is O(1) for each query because we are using precomputed sums. The space complexity is O(m * n) due to the prefix sum matrix.
- 1Using a prefix sum matrix allows for efficient range queries.
- 2Understanding the inclusion-exclusion principle is crucial for calculating sums in submatrices.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.