Python 1476.py
class SubrectangleQueries:
def __init__(self, rectangle: List[List[int]]):
self.original = rectangle
self.updates = []
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
self.updates.append(( row1, col1, row2, col2, newValue ))
def getValue(self, row: int, col: int) -> int:
# scan updates in reverse order
for i in range(len(self.updates) - 1, -1, -1):
row1, col1, row2, col2, value = self.updates[i]
if row1 <= row <= row2 and col1 <= col <= col2:
return value
# fallback to the original grid
return self.original[row][col]
Difficulty
and has an acceptance rate of about 86% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Design
- Matrix
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The SubrectangleQueries class provides a lightweight mechanism to query values in a two-dimensional integer grid after a series of sub-rectangle updates. The design separates the immutable original matrix from a mutable list of update operations, allowing updates to be recorded without altering the base data structure. Queries are answered by walking the recorded updates in reverse order, returning the most recent value that applies to the requested cell, and defaulting to the original matrix when no update covers the cell.
Construction
The constructor captures the initial state of the rectangle and prepares a container for future updates.
class SubrectangleQueries:
def __init__(self, rectangle: List[List[int]]):
self.original = rectangle
self.updates = []
self.originalholds a reference to the supplied matrix, preserving the initial values for fallback queries.self.updatesis an empty list that will accumulate tuples describing each update operation.
Recording an Update
When a sub-rectangle needs to be changed, the updateSubrectangle method stores the operation as a tuple. No immediate modification of the matrix occurs.
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
self.updates.append((row1, col1, row2, col2, newValue))
The tuple captures the inclusive bounds of the rectangle (row1, col1, row2, col2) together with the newValue that should appear in every cell of that region. By appending to self.updates, the method preserves the chronological order of updates, which is essential for later query resolution.
Querying a Cell
The getValue method determines the current value at a specific coordinate. It iterates over the stored updates in reverse, checking whether the coordinate lies inside each rectangle. The first matching update supplies the answer; otherwise, the original matrix value is returned.
def getValue(self, row: int, col: int) -> int:
# scan updates in reverse order
for i in range(len(self.updates) - 1, -1, -1):
row1, col1, row2, col2, value = self.updates[i]
if row1 <= row <= row2 and col1 <= col <= col2:
return value
# fallback to the original grid
return self.original[row][col]
Reverse Scan Logic
The loop starts from the most recent update (len(self.updates) - 1) and moves backward. This ordering guarantees that the first rectangle encountered that contains the target cell reflects the latest modification, satisfying the “last write wins” semantics.
Boundary Checks
The conditional row1 <= row <= row2 and col1 <= col <= col2 ensures that the method correctly identifies whether the query point falls inside the rectangle, handling edge cases where the point lies exactly on any of the rectangle’s borders.
Fallback Path
If the reverse scan completes without finding a covering rectangle, the method accesses self.original[row][col]. This path handles the scenario where no updates have been applied to the cell, as well as the case where the updates list is empty.
Edge Cases Handled
- Empty Update List - When no updates have been recorded, the reverse loop is bypassed, and the method directly returns the original cell value.
- Single-Cell Rectangles - The inclusive bounds allow updates that target a single cell (
row1 == row2andcol1 == col2). The boundary check correctly identifies the cell as covered. - Overlapping Updates - Multiple updates may intersect. Because the scan proceeds from newest to oldest, the most recent update that includes the cell determines the result, automatically resolving overlaps.
- Full-Matrix Updates - An update that spans the entire matrix (
row1 = 0, col1 = 0, row2 = maxRow, col2 = maxCol) is stored like any other rectangle. Subsequent queries will always hit this update first, unless a later, more specific update overrides it. - Out-of-Range Queries - The code assumes that callers provide valid indices; however, the boundary checks protect against accidental inclusion of out-of-range coordinates in the update matching logic, as the comparisons will simply evaluate to false.
Performance Optimizations
The implementation adopts a lazy update strategy. Instead of materializing each sub-rectangle change in the underlying matrix-a potentially expensive operation proportional to the rectangle’s area-the code records only the parameters of the change. This approach reduces the time spent in updateSubrectangle to a constant-time append operation, regardless of rectangle size.
Query time is proportional to the number of updates, but the reverse scan stops as soon as a matching rectangle is found. In typical usage patterns where recent updates are more likely to affect recent queries, the average number of inspected updates can be far lower than the total count. The use of a simple list for self.updates ensures cache-friendly iteration and minimal overhead.
By keeping a direct reference to the original matrix (self.original), the fallback path avoids any copying or reconstruction of the grid, delivering immediate access to unchanged cells. This design choice eliminates redundant memory allocation and leverages the original data layout for fast reads.
ELI5 - Simplified Explanation
Imagine a big sheet of graph paper that has different colors in each square. The very first part of this code takes that grid and keeps it safe so you can look at it later. Whenever you want to change a part of the drawing, the code does not actually color over the original grid. Instead, it creates a little sticky note that describes which rectangle you want to change and what new color you want to use inside that space. These sticky notes are saved in a stack, one on top of another.
When you want to know the color of a specific square on the grid, the code starts looking through the sticky notes from the one placed most recently. It checks to see if your chosen square is inside the area mentioned on that note. If the square is covered by a note, it tells you the color written on that note. If the code checks all the notes and sees that none of them cover your square, it simply looks at the original graph paper you started with to see what is there.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| DimitrisJim | C | ||||||||
| everthis | JS | ||||||||
| FelixFan1122 | C# | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| DimitrisJim | C | ||||||||
| everthis | JavaScript | ||||||||
| FelixFan1122 | C# | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| Krazune | C++ | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1013: Partition Array Into Three Parts With Equal Sum
- problem 1668: Maximum Repeating Substring
- problem 1736: Latest Time by Replacing Hidden Digits
- problem 1784: Check if Binary String Has at Most One Segment of Ones
- problem 2099: Find Subsequence of Length K With the Largest Sum
- problem 2383: Minimum Hours of Training to Win a Competition
- problem 2511: Maximum Enemy Forts That Can Be Captured
- problem 2739: Total Distance Traveled
- problem 331: Verify Preorder Serialization of a Binary Tree
- problem 400: Nth Digit
- problem 447: Number of Boomerangs
- problem 1828: Queries on Number of Points Inside a Circle
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality