#1314
Matrix Block Sum
MediumArrayMatrixPrefix SumPrefix SumMatrix Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n * (2k + 1)²) | O(m * n) |
| Space | O(1) | O(m * n) |
💡
Intuition
Time O(m * n)Space O(m * n)
Using a prefix sum array allows us to calculate the sum of any submatrix efficiently, reducing the time complexity significantly.
⚙️
Algorithm
3 steps- 1Step 1: Create a prefix sum matrix where each cell (i, j) contains the sum of all elements from (0, 0) to (i, j).
- 2Step 2: For each cell (i, j) in the result matrix, calculate the sum of the submatrix defined by (i-k, j-k) to (i+k, j+k) using the prefix sum matrix.
- 3Step 3: Handle boundaries to ensure we do not go out of bounds.
solution.py15 lines
1# Full working Python code
2
3def matrixBlockSum(mat, k):
4 m, n = len(mat), len(mat[0])
5 prefix = [[0] * (n + 1) for _ in range(m + 1)]
6 for i in range(m):
7 for j in range(n):
8 prefix[i + 1][j + 1] = mat[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]
9 result = [[0] * n for _ in range(m)]
10 for i in range(m):
11 for j in range(n):
12 r1, c1 = max(0, i - k), max(0, j - k)
13 r2, c2 = min(m - 1, i + k), min(n - 1, j + k)
14 result[i][j] = prefix[r2 + 1][c2 + 1] - prefix[r1][c2 + 1] - prefix[r2 + 1][c1] + prefix[r1][c1]
15 return resultℹ
Complexity note: The time complexity is reduced to O(m * n) because we compute the prefix sums in a single pass, and then each cell's sum can be computed in constant time. The space complexity is O(m * n) due to the prefix sum matrix.
- 1Using prefix sums allows for efficient submatrix sum calculations.
- 2Understanding boundaries is crucial when working with matrices.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.