Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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, and(r, c) is a valid position in the matrix.Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1 Output: [[12,21,16],[27,45,33],[24,39,28]]
Example 2:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2 Output: [[45,45,45],[45,45,45],[45,45,45]]
Constraints:
m == mat.lengthn == mat[i].length1 <= m, n, k <= 1001 <= mat[i][j] <= 100Problem summary: 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, and (r, c) is a valid position in the matrix.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[1,2,3],[4,5,6],[7,8,9]] 1
[[1,2,3],[4,5,6],[7,8,9]] 2
stamping-the-grid)maximum-sum-of-an-hourglass)design-neighbor-sum-service)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1314: Matrix Block Sum
class Solution {
public int[][] matrixBlockSum(int[][] mat, int k) {
int m = mat.length;
int n = mat[0].length;
int[][] s = new int[m + 1][n + 1];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
s[i + 1][j + 1] = s[i][j + 1] + s[i + 1][j] - s[i][j] + mat[i][j];
}
}
int[][] ans = new int[m][n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int x1 = Math.max(i - k, 0);
int y1 = Math.max(j - k, 0);
int x2 = Math.min(m - 1, i + k);
int y2 = Math.min(n - 1, j + k);
ans[i][j] = s[x2 + 1][y2 + 1] - s[x1][y2 + 1] - s[x2 + 1][y1] + s[x1][y1];
}
}
return ans;
}
}
// Accepted solution for LeetCode #1314: Matrix Block Sum
func matrixBlockSum(mat [][]int, k int) [][]int {
m, n := len(mat), len(mat[0])
s := make([][]int, m+1)
for i := range s {
s[i] = make([]int, n+1)
}
for i, row := range mat {
for j, x := range row {
s[i+1][j+1] = s[i][j+1] + s[i+1][j] - s[i][j] + x
}
}
ans := make([][]int, m)
for i := range ans {
ans[i] = make([]int, n)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
x1 := max(i-k, 0)
y1 := max(j-k, 0)
x2 := min(m-1, i+k)
y2 := min(n-1, j+k)
ans[i][j] = s[x2+1][y2+1] - s[x1][y2+1] - s[x2+1][y1] + s[x1][y1]
}
}
return ans
}
# Accepted solution for LeetCode #1314: Matrix Block Sum
class Solution:
def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
m, n = len(mat), len(mat[0])
s = [[0] * (n + 1) for _ in range(m + 1)]
for i, row in enumerate(mat, 1):
for j, x in enumerate(row, 1):
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + x
ans = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
x1, y1 = max(i - k, 0), max(j - k, 0)
x2, y2 = min(m - 1, i + k), min(n - 1, j + k)
ans[i][j] = (
s[x2 + 1][y2 + 1] - s[x1][y2 + 1] - s[x2 + 1][y1] + s[x1][y1]
)
return ans
// Accepted solution for LeetCode #1314: Matrix Block Sum
struct Solution;
impl Solution {
fn matrix_block_sum(mat: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> {
let n = mat.len();
let m = mat[0].len();
let mut prefix: Vec<Vec<i32>> = vec![vec![0; m]; n];
let mut res: Vec<Vec<i32>> = vec![vec![0; m]; n];
for i in 0..n {
for j in 0..m {
prefix[i][j] += mat[i][j];
if i > 0 {
prefix[i][j] += prefix[i - 1][j];
}
if j > 0 {
prefix[i][j] += prefix[i][j - 1];
}
if i > 0 && j > 0 {
prefix[i][j] -= prefix[i - 1][j - 1];
}
}
}
for i in 0..n {
for j in 0..m {
let l = j as i32 - k;
let r = j as i32 + k;
let t = i as i32 - k;
let b = i as i32 + k;
let l = if l < 0 { 0 } else { l as usize };
let r = if r >= m as i32 { m - 1 } else { r as usize };
let t = if t < 0 { 0 } else { t as usize };
let b = if b >= n as i32 { n - 1 } else { b as usize };
res[i][j] = Self::sum(t, l, b, r, &prefix);
}
}
res
}
fn sum(t: usize, l: usize, b: usize, r: usize, prefix: &[Vec<i32>]) -> i32 {
let mut res = prefix[b][r];
if l > 0 {
res -= prefix[b][l - 1];
}
if t > 0 {
res -= prefix[t - 1][r];
}
if l > 0 && t > 0 {
res += prefix[t - 1][l - 1];
}
res
}
}
#[test]
fn test() {
let mat = vec_vec_i32![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let k = 1;
let res = vec_vec_i32![[12, 21, 16], [27, 45, 33], [24, 39, 28]];
assert_eq!(Solution::matrix_block_sum(mat, k), res);
let mat = vec_vec_i32![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let k = 2;
let res = vec_vec_i32![[45, 45, 45], [45, 45, 45], [45, 45, 45]];
assert_eq!(Solution::matrix_block_sum(mat, k), res);
}
// Accepted solution for LeetCode #1314: Matrix Block Sum
function matrixBlockSum(mat: number[][], k: number): number[][] {
const m: number = mat.length;
const n: number = mat[0].length;
const s: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
s[i + 1][j + 1] = s[i][j + 1] + s[i + 1][j] - s[i][j] + mat[i][j];
}
}
const ans: number[][] = Array.from({ length: m }, () => Array(n).fill(0));
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
const x1: number = Math.max(i - k, 0);
const y1: number = Math.max(j - k, 0);
const x2: number = Math.min(m - 1, i + k);
const y2: number = Math.min(n - 1, j + k);
ans[i][j] = s[x2 + 1][y2 + 1] - s[x1][y2 + 1] - s[x2 + 1][y1] + s[x1][y1];
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.