Problem 304

Abstract / Summary

Store a 2d prefix sum table during initialization to quickly compute the sum of any subrectangle.

Note

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

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
20 lines | 843 bytes | submitted September 18, 2023 | GitHub   27% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (800k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Design
  • Matrix
  • Prefix Sum
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 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.

written by openai gpt

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.

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.11 | σ = 1.03

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 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++
43 links | 27 authors | 9 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Range Sum Query 2D | Leetcode #304'
Techdose 16 mins
Range Sum Query 2D | Leetcode #304
YouTube video 'Range Sum Query 2D - Immutable | Live Coding with Explanation | Leetcode - 304'
Algorithms Made Easy 8 mins
Range Sum Query 2D - Immutable | Live Coding with Explanation | Leetcode - 304
YouTube video 'LeetCode 304. - Range Sum Query 2D - Immutable [Algorithm + Code Explained ]'
jayati tiwari 14 mins
LeetCode 304. - Range Sum Query 2D - Immutable [Algorithm + Code Explained ]
YouTube video 'Range Sum Query 2D - Immutable | Leetcode 304 | Live coding session'
Coding Decoded 16 mins
Range Sum Query 2D - Immutable | Leetcode 304 | Live coding session
YouTube video '304. Range Sum Query 2D - Immutable | LEETCODE MEDIUM | PREFIX SUM'
code Explainer 13 mins
304. Range Sum Query 2D - Immutable | LEETCODE MEDIUM | PREFIX SUM
YouTube video 'Range Sum Query 2D - Immutable | Leetcode 304 |  Dynamic Programming |  Live coding session 🔥🔥'
Coding Decoded 4 mins
Range Sum Query 2D - Immutable | Leetcode 304 | Dynamic Programming | Live coding session 🔥🔥
YouTube video 'Daily Leetcode #794: Jun 03, 2022 - 304. Range Sum Query 2D - Immutable'
Programming Live with Larry 14 mins
Daily Leetcode #794: Jun 03, 2022 - 304. Range Sum Query 2D - Immutable
YouTube video 'Range Sum Query 2D - Immutable | LeetCode 304 | Coders Camp'
Coders Camp 14 mins
Range Sum Query 2D - Immutable | LeetCode 304 | Coders Camp
YouTube video 'Google Coding Interview Question | Leetcode 304 | Range Sum Query 2D - Immutable'
WorkWithGoogler 22 mins
Google Coding Interview Question | Leetcode 304 | Range Sum Query 2D - Immutable
YouTube video 'Daily Leetcode #407: May 12, 2021 - 304. Range Sum Query 2D - Immutable'
Programming Live with Larry 20 mins
Daily Leetcode #407: May 12, 2021 - 304. Range Sum Query 2D - Immutable
YouTube video '304. Range Sum Query 2D - Immutable || Medium || Matrix || Cpp'
Komal Pal 16 mins
304. Range Sum Query 2D - Immutable || Medium || Matrix || Cpp
YouTube video '14. Leetcode 304. Range Sum Query 2D - Immutable : JAVA'
Web Fusion with Bharadwaj 19 mins
14. Leetcode 304. Range Sum Query 2D - Immutable : JAVA
YouTube video 'Leetcode 304. Range Sum Query 2D - Immutable'
The Loop Head 15 mins
Leetcode 304. Range Sum Query 2D - Immutable
YouTube video 'LeetCode 304. [Medium]  Range Sum Query 2D - Immutable'
Francesco Manicardi 12 mins
LeetCode 304. [Medium] Range Sum Query 2D - Immutable
YouTube video 'LeetCode 304 | Range Sum Query 2D - Immutable | PrevSum | Java'
Sleepy Cracker 7 mins
LeetCode 304 | Range Sum Query 2D - Immutable | PrevSum | Java
YouTube video '44. LeetCode 304. Range Sum Query 2D  Immutable [ JAVASCRIPT ]'
Web Fusion with Bharadwaj 7 mins
44. LeetCode 304. Range Sum Query 2D Immutable [ JAVASCRIPT ]
YouTube video 'Leetcode Question 304 "Range Sum Query 2D - Immutable" in Java'
Ghumman Tech 13 mins
Leetcode Question 304 "Range Sum Query 2D - Immutable" in Java
17 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 easy
2 solutions   September 18, 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