Subrectangle Queries - Problem
Imagine you're building a dynamic matrix editor that needs to efficiently handle two types of operations: bulk updates and single-cell queries. This is exactly what the SubrectangleQueries class does!
Your task is to implement a class that manages a 2D matrix and supports:
- updateSubrectangle(row1, col1, row2, col2, newValue): Update all cells in the rectangular region from top-left corner
(row1, col1)to bottom-right corner(row2, col2)with the same value. - getValue(row, col): Retrieve the current value at position
(row, col).
Example:
matrix = [[1,2,1],[4,3,4]]
updateSubrectangle(0, 0, 1, 2, 5) โ [[5,5,5],[5,5,5]]
getValue(0, 2) โ 5
The challenge is to balance update efficiency vs query efficiency based on the expected usage patterns!
Input & Output
example_1.py โ Basic Operations
$
Input:
SubrectangleQueries([[1,2,1],[4,3,4]])
updateSubrectangle(0, 0, 1, 2, 5)
getValue(0, 2)
getValue(1, 1)
updateSubrectangle(1, 0, 1, 2, 10)
getValue(1, 0)
โบ
Output:
[null, null, 5, 5, null, 10]
๐ก Note:
Initially matrix is [[1,2,1],[4,3,4]]. After first update, all cells become 5. After second update, bottom row becomes [10,10,10].
example_2.py โ Single Cell Update
$
Input:
SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]])
updateSubrectangle(0, 0, 0, 0, 100)
getValue(0, 0)
getValue(0, 1)
โบ
Output:
[null, null, 100, 1]
๐ก Note:
Only the top-left corner (0,0) is updated to 100. Other cells retain original values.
example_3.py โ Overlapping Updates
$
Input:
SubrectangleQueries([[1,2],[3,4]])
updateSubrectangle(0, 0, 1, 1, 5)
updateSubrectangle(0, 0, 0, 1, 10)
getValue(0, 0)
getValue(1, 0)
โบ
Output:
[null, null, null, 10, 5]
๐ก Note:
First update makes all cells 5. Second update overwrites top row to 10. getValue(0,0) returns 10 from most recent update, getValue(1,0) returns 5 from first update.
Constraints
- 1 โค rows, cols โค 100
- 1 โค rectangle[i][j] โค 109
- 0 โค row1 โค row2 < rows
- 0 โค col1 โค col2 < cols
- 1 โค newValue โค 109
- At most 500 calls will be made to updateSubrectangle and getValue
Visualization
Tap to expand
Understanding the Visualization
1
Direct Painting
Paint each cell immediately - slow to paint, fast to see color
2
Paint Instructions
Write down paint instructions - fast to write, need to check instructions when viewing
3
Trade-off Analysis
Choose strategy based on whether you paint more or look more often
Key Takeaway
๐ฏ Key Insight: The optimal approach depends on your access pattern. With at most 500 total operations, the lazy approach often wins due to its O(1) update time, making it ideal for scenarios with bulk updates followed by targeted queries.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code