You are given a positive integer n, indicating that we initially have an n x n0-indexed integer matrix mat filled with zeroes.
You are also given a 2D integer array query. For each query[i] = [row1i, col1i, row2i, col2i], you should do the following operation:
Add 1 to every element in the submatrix with the top left corner (row1i, col1i) and the bottom right corner (row2i, col2i). That is, add 1 to mat[x][y] for all row1i <= x <= row2i and col1i <= y <= col2i.

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).

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.
Directly incrementing all elements in each submatrix for every query is too slow. Instead, we use a 2D prefix sum trick (Imos method) to efficiently apply all increments, then compute the final matrix in one pass.
funrangeAddQueries(n: Int, queries: Array<IntArray>): Array<IntArray> {
val diff = Array(n+1) { IntArray(n+1) }
for (q in queries) {
val(r1, c1, r2, c2) = q
diff[r1][c1]++ diff[r1][c2+1]-- diff[r2+1][c1]-- diff[r2+1][c2+1]++ }
for (i in0 until n)
for (j in1 until n)
diff[i][j] += diff[i][j-1]
for (j in0 until n)
for (i in1 until n)
diff[i][j] += diff[i-1][j]
val ans = Array(n) { IntArray(n) }
for (i in0 until n)
for (j in0 until n)
ans[i][j] = diff[i][j]
return ans
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
defrangeAddQueries(n: int, queries: list[list[int]]) -> list[list[int]]:
diff = [[0]*(n+1) for _ in range(n+1)]
for r1, c1, r2, c2 in queries:
diff[r1][c1] +=1 diff[r1][c2+1] -=1 diff[r2+1][c1] -=1 diff[r2+1][c2+1] +=1for i in range(n):
for j in range(1, n):
diff[i][j] += diff[i][j-1]
for j in range(n):
for i in range(1, n):
diff[i][j] += diff[i-1][j]
ans = [[diff[i][j] for j in range(n)] for i in range(n)]
return ans