Python 0304.py
class NumMatrix:
def __init__(self, matrix: List[List[int]]):
# 2D prefix sum
for y in range(len(matrix)):
for x in range(1, len(matrix[0])):
matrix[y][x] += matrix[y][x-1]
for y in range(1, len(matrix)):
for x in range(len(matrix[0])):
matrix[y][x] += matrix[y-1][x]
self.prefix = matrix
def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
result = self.prefix[row2][col2] # full area
if row1 > 0:
result -= self.prefix[row1 - 1][col2] # minus left
if col1 > 0:
result -= self.prefix[row2][col1 - 1] # minus upper
if row1 > 0 and col1 > 0:
result += self.prefix[row1 - 1][col1 - 1] # upper-left was subtracted twice
return result
Difficulty
and has an acceptance rate of about 59% (800k+ submissions).
Typical patterns to solve this problem:
- Array
- Design
- Matrix
- Prefix Sum
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 class implements a two-dimensional range-sum query structure using a prefix-sum matrix. The constructor transforms the input matrix in-place into a cumulative sum representation, and the sumRegion method retrieves the sum of any sub-rectangle in constant time by applying the inclusion-exclusion principle.
Construction of the Prefix Matrix
The first phase builds row-wise cumulative sums. For each row y, the inner loop starts at column 1 and adds the value of the previous column to the current cell. This propagates the sum of all elements to the left of the current position.
for y in range(len(matrix)):
for x in range(1, len(matrix[0])):
matrix[y][x] += matrix[y][x-1]
The second phase extends the accumulation vertically. Starting from row 1, each cell receives the sum of the cell directly above it, turning the row-wise totals into full two-dimensional prefix sums.
for y in range(1, len(matrix)):
for x in range(len(matrix[0])):
matrix[y][x] += matrix[y-1][x]
After these two passes, matrix[y][x] holds the sum of all elements in the rectangle from the origin (0,0) to (y,x). The transformed matrix is stored as self.prefix.
Querying a Sub-Rectangle
The sumRegion method computes the sum of the rectangle defined by its upper-left corner (row1, col1) and lower-right corner (row2, col2). It begins with the total sum of the area from the origin to (row2, col2) and then subtracts the excess portions that lie above or to the left of the requested region. When both a top and a left excess exist, the overlapping upper-left block has been subtracted twice, so it is added back once.
result = self.prefix[row2][col2] # full area
if row1 > 0:
result -= self.prefix[row1 - 1][col2] # remove rows above
if col1 > 0:
result -= self.prefix[row2][col1 - 1] # remove columns left
if row1 > 0 and col1 > 0:
result += self.prefix[row1 - 1][col1 - 1] # compensate double subtraction
return result
Edge Cases Handled
When the query touches the top edge (row1 == 0), the subtraction of rows above is skipped because there are none. Similarly, when the query touches the left edge (col1 == 0), the column subtraction is omitted. The combined condition row1 > 0 and col1 > 0 ensures that the correction for double subtraction is only applied when both excess regions exist.
If the input matrix contains a single row or a single column, the loops still execute correctly: the row-wise pass processes the single row, and the column-wise pass either runs zero times (for a single row) or processes the single column (for a single column). An empty matrix would result in len(matrix) or len(matrix[0]) being zero; the loops naturally perform no iterations, leaving self.prefix as an empty list, and any subsequent query would be out of bounds, which is consistent with the expected contract of the class.
Performance Optimizations
The implementation reuses the original matrix to store the prefix sums, eliminating the need for an auxiliary data structure and reducing memory overhead. The two-pass approach-first horizontal then vertical-leverages cache-friendly access patterns: each pass iterates row-major, accessing contiguous memory locations, which improves locality.
By precomputing the cumulative sums, each sumRegion call performs only a constant number of arithmetic operations and array lookups, regardless of the rectangle size. This makes the query operation extremely fast compared to a naïve summation that would iterate over every element in the region.
The conditional checks (if row1 > 0, if col1 > 0) avoid unnecessary array accesses when the query aligns with the matrix borders, preventing redundant memory reads. This subtle guard contributes to overall efficiency, especially when many queries involve edge-aligned rectangles.
ELI5 - Simplified Explanation
Imagine a big sheet of paper covered in square tiles, and each tile has a number written on it. This code acts like a very fast calculator that helps find the total of all the numbers inside any rectangular shape on that sheet.
First, the code goes through every tile one by one and adds the numbers together in a special way. It turns each tile into a box that holds the sum of everything from the top-left corner all the way down to that spot. It is like having a backpack where you collect all the toys you see as you walk across the room. By the time it finishes this, every spot on the grid knows the total value of the entire area above and to the left of it.
When you want to know the sum of a specific section, the code uses a neat shortcut. It takes the total value from the bottom-right corner of your chosen rectangle. Since that big pile includes extra tiles you do not want, it subtracts the parts that are above and to the left of your rectangle. If it accidentally takes away the top-left corner piece too many times during this subtraction, it simply adds that little piece back once to make the math perfectly balanced. Through this clever dance of adding and subtracting, it finds the answer in a split second.
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 | Rust | JS | Java | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | aylei | Rust | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 303: Range Sum Query - Immutable
Solved On The Same Day
- problem 1337: The K Weakest Rows in a Matrix
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