Python 1314.py
class Solution:
def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
height = len(mat)
width = len(mat[0])
# 2D prefix sum
prefix = mat.copy()
for y in range(height):
for x in range(1, width):
prefix[y][x] += prefix[y][x - 1]
for y in range(1, height):
for x in range(width):
prefix[y][x] += prefix[y - 1][x]
result = [ [ 0 ] * width for _ in range(height) ]
for y in range(height):
for x in range(width):
# prefix sums at each corners must be added/subtracted
# ++++-----
# ++++-----
# ----+++++
# ----+++++
left = x - k
right = min(width - 1, x + k)
up = y - k
down = min(height - 1, y + k)
total = prefix[down][right]
if left > 0:
total -= prefix[down][left - 1]
if up > 0:
total -= prefix[up - 1][right]
if left > 0 and up > 0:
total += prefix[up - 1][left - 1]
result[y][x] = total
return result
Difficulty
and has an acceptance rate of about 77% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- 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 provided implementation computes the block sum of a matrix for a given radius k. For each cell it returns the sum of all elements that lie within a square centered at that cell, extending k positions in every direction. The algorithm relies on a two-dimensional prefix sum to answer each block query in constant time after a linear-time preprocessing phase.
Key Steps
Determining Matrix Dimensions
The first two statements capture the height and width of the input matrix.
height = len(mat)
width = len(mat[0])
These values are used throughout the algorithm to bound index calculations.
Building the 2D Prefix Sum
A copy of the original matrix is taken as the working array for the prefix sums. The first nested loop accumulates row-wise sums, turning each entry into the sum of all elements to its left in the same row.
prefix = mat.copy()
for y in range(height):
for x in range(1, width):
prefix[y][x] += prefix[y][x - 1]
The second nested loop then propagates these row sums vertically, converting each cell into the sum of the rectangle from the origin (0,0) to that cell.
for y in range(1, height):
for x in range(width):
prefix[y][x] += prefix[y - 1][x]
After these two passes, prefix[y][x] holds the total of all matrix elements whose row index ≤ y and column index ≤ x.
Preparing the Result Container
A matrix of zeros with the same dimensions is allocated to store the final block sums.
result = [ [ 0 ] * width for _ in range(height) ]
Computing Each Block Sum
The core double loop iterates over every cell (y, x). For each position it determines the inclusive boundaries of the square block, clamping them to the matrix edges.
left = x - k
right = min(width - 1, x + k)
up = y - k
down = min(height - 1, y + k)
Using the prefix matrix, the sum of the rectangle defined by (up, left) and (down, right) is obtained with inclusion-exclusion. The code subtracts the contributions of the regions left of left and above up, then adds back the overlapping corner that was subtracted twice.
total = prefix[down][right]
if left > 0:
total -= prefix[down][left - 1]
if up > 0:
total -= prefix[up - 1][right]
if left > 0 and up > 0:
total += prefix[up - 1][left - 1]
The computed total is stored in the corresponding entry of the result matrix.
result[y][x] = total
Finally, the populated result matrix is returned.
return result
Edge Cases Handled
When the requested block extends beyond the matrix borders, the min calls ensure that right and down never exceed the last valid column or row. The conditions if left > 0 and if up > 0 guard against negative indices when the block starts before the first column or row. Consequently, the algorithm correctly returns the sum of the available portion of the block for cells near the edges, including corners and sides.
If k is zero, the boundaries collapse to the cell itself (left == right == x, up == down == y). The inclusion-exclusion logic reduces to returning the original element, because the prefix subtraction steps are bypassed.
The code also works for matrices with a single row or a single column. In those scenarios the row-wise or column-wise accumulation loops still execute correctly, and the boundary calculations adapt to the one-dimensional shape.
Performance Optimizations
The implementation builds the prefix sum in-place by reusing the original matrix storage (prefix = mat.copy()). This avoids allocating an additional matrix of the same size, reducing memory pressure.
Row-wise accumulation is performed before column-wise accumulation, which allows each inner loop to operate on contiguous memory locations, improving cache locality.
During block sum computation, the algorithm accesses at most four entries from the prefix matrix per cell, regardless of k. By pre-computing the clamped boundaries (right, down) with min, it eliminates the need for repeated conditional checks inside the inner loop.
The use of simple integer arithmetic and direct indexing ensures that the inner work per cell remains minimal, contributing to a fast overall execution.
ELI5 - Simplified Explanation
Imagine a big box of square blocks laid out on the floor like a giant grid. Some blocks have different values written on them. This code is like a helper that looks at a specific block and adds up all the values of the squares that are close by.
First, the code makes a special map. It goes row by row and then column by column to add up all the numbers so that if you want to know the sum of a whole rectangle, you can find it very quickly without counting every single block one by one every time. It keeps a running total of everything it sees.
Next, the code starts looking at every single spot in the grid. For each spot, it thinks about a window that stretches out a certain distance in all four directions. Since the window might go off the edge of the grid, it uses a trick to make sure it only looks at the spots that really exist.
To get the final sum for each spot, the code takes the total from the special map and does some simple math with the corners of that window. By subtracting the parts that are outside the window and adding back the little corner that got taken away twice, it finds the sum of all the blocks inside the window perfectly. It finishes by coloring in a new grid with these totals so the answer is ready to see.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
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 | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| 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 | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# |
Videos
Similar Problems
- problem 2132: Stamping the Grid
- problem 2428: Maximum Sum of an Hourglass
Solved On The Same Day
- problem 1905: Count Sub Islands
- problem 2024: Maximize the Confusion of an Exam
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