Skip to content
MediumArraysAI interview only

Matrix Block Sum

Asked atgoogleamazonmeta

01 · Problem

Given an m x n integer matrix mat and an integer k, return a matrix answer of the same size where answer[i][j] is the sum of every mat[r][c] with:

  • i - k <= r <= i + k
  • j - k <= c <= j + k
  • (r, c) is a valid cell inside the matrix

In other words, each output cell holds the sum of the square block of radius k centred on it, clipped at the matrix edges.

02 · Examples

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

answer[0][0] sums the clipped block rows 0..1, cols 0..1: 1+2+4+5 = 12. answer[1][1] covers the whole matrix: 45.

Example 02
Input
mat = [[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 block covers the entire 3x3 matrix, so every cell is 45.

Example 03
Input
mat = [[1,1,1,1]], k = 1
Output
[[2,3,3,2]]

Single row: each block covers the cell and up to one neighbour on each side (3 cells); the two ends see only 2 cells.

03 · Constraints

  • 01m == mat.length
  • 02n == mat[i].length
  • 031 <= m, n, k <= 100
  • 041 <= mat[i][j] <= 100

04 · Optimal complexity

Time
O(m * n)
Space
O(m * n)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.