Matrix Block Sum Problem
Description
LeetCode Problem 1314.
Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:
i - k <= r <= i + k,j - k <= c <= j + k, and(r, c)is a valid position in the matrix.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[12,21,16],[27,45,33],[24,39,28]]
Example 2:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
Output: [[45,45,45],[45,45,45],[45,45,45]]
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n, k <= 1001 <= mat[i][j] <= 100
Solution
Approach: 2D Prefix Sums
Adding up each block directly costs O(k2) per cell. With 2D prefix sums, every block sum takes four lookups.
Let s[i][j] be the sum of the top-left corner mat[0..i - 1][0..j - 1], with a row and a column of zeros in front. It is built in one pass:
s[i + 1][j + 1] = s[i][j + 1] + s[i + 1][j] - s[i][j] + mat[i][j]
The two smaller corners overlap in s[i][j], which is counted twice and so subtracted once.
The sum of any rectangle with rows r1..r2 - 1 and columns c1..c2 - 1 then follows the same inclusion-exclusion idea: s[r2][c2] - s[r1][c2] - s[r2][c1] + s[r1][c1].
For cell (i, j), the block runs from i - k to i + k and from j - k to j + k, but the problem only counts the part inside the matrix. Clipping the bounds first (r1 = max(0, i - k), r2 = min(m, i + k + 1), and the same for columns) handles the edges; in Example 2, k = 2 covers the whole 3 x 3 matrix from every cell, so every answer is 45.
Complexity: O(m * n) time and O(m * n) space for the prefix sums.
class Solution:
def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
m, n = len(mat), len(mat[0])
# s[i][j] is the sum of the top-left i x j corner, mat[0..i-1][0..j-1].
s = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m):
for j in range(n):
s[i + 1][j + 1] = s[i][j + 1] + s[i + 1][j] - s[i][j] + mat[i][j]
ans = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
# Clip the block to the matrix, then take its sum from four corners.
r1, c1 = max(0, i - k), max(0, j - k)
r2, c2 = min(m, i + k + 1), min(n, j + k + 1)
ans[i][j] = s[r2][c2] - s[r1][c2] - s[r2][c1] + s[r1][c1]
return ans