Increment Submatrices by One Problem
Description
LeetCode Problem 2536.
You are given a positive integer n, indicating that we initially have an n x n 0-indexed integer matrix mat filled with zeroes.
You are also given a 2D integer array query. For each query[i] = [row1_i, col1_i, row2_i, col2_i], you should do the following operation:
- Add
1to every element in the submatrix with the top left corner(row1_i, col1_i)and the bottom right corner(row2_i, col2_i). That is, add1tomat[x][y]for allrow1_i <= x <= row2_iandcol1_i <= y <= col2_i.
Return the matrix mat after performing every query.
Example 1:

Input: n = 3, queries = [[1,1,2,2],[0,0,1,1]]
Output: [[1,1,0],[1,2,1],[0,1,1]]
Explanation: The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.
- In the first query, we add 1 to every element in the submatrix with the top left corner (1, 1) and bottom right corner (2, 2).
- In the second query, we add 1 to every element in the submatrix with the top left corner (0, 0) and bottom right corner (1, 1).
Example 2:

Input: n = 2, queries = [[0,0,1,1]]
Output: [[1,1],[1,1]]
Explanation: The diagram above shows the initial matrix and the matrix after the first query.
- In the first query we add 1 to every element in the matrix.
Constraints:
1 <= n <= 5001 <= queries.length <= 10^40 <= row1_i <= row2_i < n0 <= col1_i <= col2_i < n
Solution
Approach: 2D Difference Array
Adding 1 to every cell of a rectangle one query at a time is too slow. Instead record each query as four corner marks in a matrix diff, and add everything up once at the end.
For a query [r1, c1, r2, c2]:
- add 1 at
(r1, c1); - subtract 1 at
(r2 + 1, c1)and at(r1, c2 + 1), when those cells exist; - add 1 at
(r2 + 1, c2 + 1), when it exists.
Then a 2D prefix sum turns the marks into the final values: each cell is its own mark plus the cell above plus the cell on the left, minus the cell diagonally above-left. The marks make exactly the cells inside each rectangle gain 1.
Complexity: O(q + n2) time for q queries, and O(1) extra space beyond the answer matrix.
class Solution:
def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:
mat = [[0] * n for _ in range(n)]
for x1, y1, x2, y2 in queries:
mat[x1][y1] += 1
if x2 + 1 < n:
mat[x2 + 1][y1] -= 1
if y2 + 1 < n:
mat[x1][y2 + 1] -= 1
if x2 + 1 < n and y2 + 1 < n:
mat[x2 + 1][y2 + 1] += 1
for i in range(n):
for j in range(n):
if i:
mat[i][j] += mat[i - 1][j]
if j:
mat[i][j] += mat[i][j - 1]
if i and j:
mat[i][j] -= mat[i - 1][j - 1]
return mat