Matrix Block Sum - 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
  • (r, c) is a valid position in the matrix

In other words, for each cell in the matrix, calculate the sum of all elements within a square block of radius k centered at that cell.

Input & Output

Example 1 — Basic 3×3 Matrix
$ Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[12,21,16],[27,45,33],[24,39,28]]
💡 Note: For cell (1,1): sum of 3×3 block = 1+2+3+4+5+6+7+8+9 = 45. For corner (0,0): sum of available 2×2 block = 1+2+4+5 = 12.
Example 2 — Larger Radius
$ Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
Output: [[45,45,45],[45,45,45],[45,45,45]]
💡 Note: With k=2, every cell's block covers the entire 3×3 matrix, so all results are 45 (sum of entire matrix).
Example 3 — Single Cell
$ Input: mat = [[5]], k = 1
Output: [[5]]
💡 Note: Single cell matrix: the only block sum is the cell itself = 5.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 ≤ m, n ≤ 500
  • 1 ≤ k ≤ 500
  • -104 ≤ mat[i][j] ≤ 104

Visualization

Tap to expand
Matrix Block Sum: Calculate k-radius Block SumsInput Matrix123456789k = 1ProcessOutput Matrix122116274533243928Block sumsEach cell shows sum of k-radius neighborhoodCenter cell (1,1): sum of entire 3×3 matrix = 45🎯 Key Insight: Use 2D prefix sums to avoid recalculating overlapping regions
Understanding the Visualization
1
Input
3×3 matrix with k=1 radius
2
Process
For each cell, sum elements in k-radius square
3
Output
Matrix with block sums
Key Takeaway
🎯 Key Insight: Pre-compute 2D prefix sums to calculate any rectangular sum in O(1) time using inclusion-exclusion principle
Asked in
Facebook 35 Google 28 Amazon 22
34.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen