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
šŸØ Smart Hotel Lighting Control SystemStep 1: Control Points+1-1-1+1Step 2: Signal PropagationFinal Result: Optimal Lighting110110000
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!
Asked in
Google 42 Amazon 35 Microsoft 28 Meta 22
73.9K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
šŸ’” Explanation
AI Ready
šŸ’” Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen