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 INPUT mat (3x3 matrix), k = 1 1 2 3 4 5 6 7 8 9 Block for cell (1,1) with k=1: 1 2 3 4 5 6 7 8 9 Sum = 1+2+3+4+5+6+7+8+9 = 45 ALGORITHM STEPS 1 Build Prefix Sum Create prefix sum matrix P[i][j] = sum of mat[0..i][0..j] 1 3 6 5 12 21 12 27 45 Prefix Sum P 2 Find Block Bounds r1=max(0,i-k), c1=max(0,j-k) r2=min(m-1,i+k), c2=min(n-1,j+k) 3 Calculate Block Sum Use inclusion-exclusion: P[r2][c2] - P[r1-1][c2] - P[r2][c1-1] + P[r1-1][c1-1] 4 Fill Result Matrix Repeat for all cells Time: O(m*n), Space: O(m*n) O(m*n) FINAL RESULT answer matrix: 12 21 16 27 45 33 24 39 28 Example Calculations: ans[0][0]: sum of block (0,0) to (1,1) = 1+2+4+5 = 12 ans[1][1]: sum of entire matrix = 45 ans[2][2]: sum of block (1,1) to (2,2) = 5+6+8+9 = 28 OK Key Insight: Using 2D prefix sums allows calculating any rectangular block sum in O(1) time. The formula: BlockSum(r1,c1,r2,c2) = P[r2][c2] - P[r1-1][c2] - P[r2][c1-1] + P[r1-1][c1-1] This avoids the naive O(k^2) per cell approach, reducing total time from O(m*n*k^2) to O(m*n). TutorialsPoint - Matrix Block Sum | Prefix Sum Approach (Optimal)
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