Subrectangle Queries - Problem

Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:

1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)

Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).

2. getValue(int row, int col)

Returns the current value of the coordinate (row,col) from the rectangle.

Input & Output

Example 1 — Basic Operations
$ Input: [["SubrectangleQueries",[[1,2,1],[4,3,4],[3,2,1]]],["getValue",[0,2]],["updateSubrectangle",[0,0,2,2,5]],["getValue",[0,2]],["getValue",[2,1]]]
Output: [null,1,null,5,5]
💡 Note: Initialize with matrix [[1,2,1],[4,3,4],[3,2,1]], getValue(0,2) returns 1, update subrectangle to 5, getValue(0,2) now returns 5, getValue(2,1) returns 5
Example 2 — Multiple Updates
$ Input: [["SubrectangleQueries",[[1,1,1],[2,2,2],[3,3,3]]],["updateSubrectangle",[0,0,1,1,10]],["getValue",[0,0]],["updateSubrectangle",[1,1,2,2,20]],["getValue",[1,1]]]
Output: [null,null,10,null,20]
💡 Note: First update sets top-left 2x2 to 10, second update overlaps and sets bottom-right 2x2 to 20
Example 3 — Edge Case Single Cell
$ Input: [["SubrectangleQueries",[[5]]],["getValue",[0,0]],["updateSubrectangle",[0,0,0,0,3]],["getValue",[0,0]]]
Output: [null,5,null,3]
💡 Note: Single cell matrix, getValue returns 5, update single cell to 3, getValue returns 3

Constraints

  • 1 ≤ rows, cols ≤ 100
  • 0 ≤ row1 ≤ row2 < rows
  • 0 ≤ col1 ≤ col2 < cols
  • 1 ≤ newValue, rectangle[i][j] ≤ 109
  • At most 500 calls to updateSubrectangle and getValue

Visualization

Tap to expand
Subrectangle Queries: Matrix Operations1. Initialize Matrix:1214343212. Update (0,0,2,2) → 5:5555555553. Query Operations:getValue(0,2) → 5 | getValue(2,1) → 5
Understanding the Visualization
1
Initialize
Create matrix with given values
2
Update
Modify rectangular region with new value
3
Query
Retrieve value at specific position
Key Takeaway
🎯 Key Insight: Choose between direct matrix updates (simple) or update history tracking (efficient for frequent updates)
Asked in
Google 12 Amazon 8 Microsoft 6
25.3K Views
Medium Frequency
~15 min Avg. Time
892 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