medium +25 pts

Matrix Block Sum

Compute block sums for every position in a matrix with a given radius.

You are given a 2D list `mat` (list of lists of integers) with dimensions `m x n`, and an integer `k`. For each cell `(i, j)`, define the block centered at that cell with radius `k`. The block includes all cells `(r, c)` such that `max(|r - i|, |c - j|) <= k`. Cells outside the matrix boundaries are treated as 0. Your task is to return a new matrix `answer` of the same dimensions where `answer[i][j]` is the sum of all cells in the block centered at `(i, j)`. Implement the function `matrix_block_sum(mat, k)` that returns the resulting matrix as a list of lists of integers.

Constraints

- 1 <= m, n <= 200 - 0 <= k <= 1000 - -1000 <= mat[i][j] <= 1000 - The input matrix is always non-empty. - The sum of any block fits within a 64-bit signed integer.

Example

>>> matrix_block_sum([[1,2,3],[4,5,6],[7,8,9]], 1)
[[12, 21, 16], [27, 45, 33], [24, 39, 28]]
>>> matrix_block_sum([[1,2,3],[4,5,6],[7,8,9]], 0)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> matrix_block_sum([[1,2],[3,4]], 2)
[[10, 10], [10, 10]]
25 points ~25 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Consider using a 2D prefix sum array to quickly compute the sum of any rectangle.
For each cell, the block is the rectangle from (i-k, j-k) to (i+k, j+k), clipped to matrix bounds.
Build an (m+1) x (n+1) prefix sum where prefix[i+1][j+1] is sum of elements in rows 0..i and columns 0..j.
Use prefix sums to get rectangle sums in O(1) after O(m*n) preprocessing.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.