Compute Every Fixed-Size Submatrix Sum
CitadelSoftware Engineer · OnsiteLast updated
Compute every contiguous fixed-size submatrix sum without mutating the input, using a padded two-dimensional prefix grid to answer each window in constant time.
Problem
Given an integer matrix and an integer k, compute the sum of every contiguous k x k submatrix. Return a matrix where output cell [r][c] is the sum of the submatrix whose top-left corner is input cell [r][c].
Function Contract
Implement k_by_k_sums(matrix, k) -> list[list[int]]. Do not mutate the input.
Constraints
1 <= rows, columns <= 1000and the total cell count is at most10^6.1 <= k <= min(rows, columns).- Values lie in
[-10^9, 10^9]. - The output shape is
(rows-k+1) x (columns-k+1).
Examples
- For
[[1,2,3],[4,5,6],[7,8,9]]andk = 2, return[[12,16],[24,28]]. - When
k = 1, return a copy of the input matrix.
Edge Cases
- Negative values can make a submatrix sum negative.
- When
kequals both dimensions, the output has one cell. - Sums can exceed 32-bit range.
Hints
Hint 1
Use a padded 2D prefix sum: A prefix grid with one extra top row and left column lets one rectangle sum use four lookups without boundary branches.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.