#1476
Subrectangle Queries
MediumArrayDesignMatrixLazy PropagationArray Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of updating the rectangle directly, we can keep track of updates using a lazy propagation technique. This allows us to apply updates only when necessary, making it efficient.
⚙️
Algorithm
3 steps- 1Step 1: Create a 2D array to store the rectangle and an additional array to track updates.
- 2Step 2: For updateSubrectangle, instead of updating the rectangle directly, store the update information in a separate structure.
- 3Step 3: For getValue, check if there's an update for the specific cell and return the appropriate value.
solution.py13 lines
1class SubrectangleQueries:
2 def __init__(self, rectangle):
3 self.rectangle = rectangle
4 self.updates = []
5
6 def updateSubrectangle(self, row1, col1, row2, col2, newValue):
7 self.updates.append((row1, col1, row2, col2, newValue))
8
9 def getValue(self, row, col):
10 for (row1, col1, row2, col2, newValue) in reversed(self.updates):
11 if row1 <= row <= row2 and col1 <= col <= col2:
12 return newValue
13 return self.rectangle[row][col]ℹ
Complexity note: The time complexity for getValue is O(n) in the worst case, where n is the number of updates. The space complexity is O(n) due to storing updates.
- 1Understanding the difference between direct updates and lazy updates can significantly affect performance.
- 2Tracking updates separately allows for more efficient retrieval of values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.