Problem 1476

Abstract / Summary

You can update a rectangle in a grid and query the value at any cell after updates.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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]
17 lines | 700 bytes | submitted October 12, 2023 | GitHub   16% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 86% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Design
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.original holds a reference to the supplied matrix, preserving the initial values for fallback queries.
  • self.updates is 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 == row2 and col1 == 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.00 | σ = 1.25

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
31 links | 20 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

13 solutions   October 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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