Matrix Block Sum

Given an 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
1 2 3
4 5 6
7 8 9
Inputmat = [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output[[12,21,16],[27,45,33],[24,39,28]]
For each position, the block includes all valid cells within distance 1 in both row and column directions, producing the shown sums.
Example 2
1 2 3
4 5 6
7 8 9
Inputmat = [[1,2,3],[4,5,6],[7,8,9]], k = 2
Output[[45,45,45],[45,45,45],[45,45,45]]
With k = 2, every position's block covers the entire 3 x 3 matrix, whose sum is 45.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n, k <= 100
  • 1 <= mat[i][j] <= 100

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate