Increment Submatrices by One - Problem
šÆ Matrix Range Updates Challenge
Imagine you're managing a grid-based system where you need to efficiently process multiple range update operations. You start with an n Ć n matrix filled with zeros, and you're given a series of queries that increment rectangular regions.
Your Task: For each query [row1, col1, row2, col2], add 1 to every element in the submatrix from top-left corner (row1, col1) to bottom-right corner (row2, col2) inclusive.
Example: If you have a 3Ć3 zero matrix and query [1,1,2,2], you increment the 2Ć2 bottom-right submatrix.
š The Challenge: Can you solve this efficiently when dealing with thousands of queries on large matrices?
Input & Output
example_1.py ā Basic Range Update
$
Input:
n = 3, queries = [[1,1,2,2]]
āŗ
Output:
[[0,0,0],[0,1,1],[0,1,1]]
š” Note:
Start with 3Ć3 zero matrix. Query [1,1,2,2] increments the 2Ć2 submatrix from (1,1) to (2,2). Only the bottom-right 4 cells are incremented by 1.
example_2.py ā Multiple Overlapping Queries
$
Input:
n = 2, queries = [[0,0,1,1],[1,0,1,1]]
āŗ
Output:
[[1,1],[2,2]]
š” Note:
First query increments entire 2Ć2 matrix. Second query increments bottom row again. Cell (1,0) and (1,1) are incremented twice, resulting in value 2.
example_3.py ā Single Cell Update
$
Input:
n = 3, queries = [[0,0,0,0],[2,2,2,2]]
āŗ
Output:
[[1,0,0],[0,0,0],[0,0,1]]
š” Note:
Two single-cell updates: top-left corner (0,0) and bottom-right corner (2,2). Each gets incremented by 1, all other cells remain 0.
Constraints
- 1 ⤠n ⤠1000
- 1 ⤠queries.length ⤠5 à 104
- queries[i].length == 4
- 0 ⤠row1i ⤠row2i < n
- 0 ⤠col1i ⤠col2i < n
- All coordinates are 0-indexed
Visualization
Tap to expand
Understanding the Visualization
1
Install Control Points
Place +1 signal at top-left corner of each lighting zone
2
Add Boundary Stoppers
Place -1 signals at right and bottom boundaries to contain the effect
3
Broadcast Changes
Send cumulative signals across the grid using 2D propagation
4
Final Illumination
Each room receives the correct brightness level automatically
Key Takeaway
šÆ Key Insight: Instead of manually adjusting each room's lighting, use smart control points that automatically propagate changes across defined rectangular zones - saving massive time and energy!
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code