Matrix Block Sum — LeetCode 1314 Python Solution

MediumArrayMatrixPrefix Sum
Problem
#1314
Pattern
Prefix Sum
Reading time
3 min

The problem

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

Input
mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output
[[12,21,16],[27,45,33],[24,39,28]]

Python solution

Python
class Solution:
    def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
        m, n = len(mat), len(mat[0])
        s = [[0] * (n + 1) for _ in range(m + 1)]
        for i, row in enumerate(mat, 1):
            for j, x in enumerate(row, 1):
                s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x
        ans = [[0] * n for _ in range(m)]
        for i in range(m):
            for j in range(n):
                x1, y1 = max(i - k, 0), max(j - k, 0)
                x2, y2 = min(m - 1, i + k), min(n - 1, j + k)
                ans[i][j] = (
                    s[x2 + 1][y2 + 1] - s[x1][y2 + 1] - s[x2 + 1][y1] + s[x1][y1]
                )
        return ans

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1314. Matrix Block Sum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1314. Matrix Block Sum?
LeetCode 1314. Matrix Block Sum is rated Medium on LeetCode.
What is the time complexity of LeetCode 1314. Matrix Block Sum?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 1314. Matrix Block Sum?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 1314. Matrix Block Sum cover?
LeetCode 1314. Matrix Block Sum is tagged Array, Matrix and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview