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.
Return the matrixmat 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 <= 500
1 <= queries.length <= 104
0 <= row1i <= row2i < n
0 <= col1i <= col2i < n
Solutions
Solution 1: 2D Difference Array
A 2D difference array is a technique used to efficiently handle range updates on 2D arrays. We can implement fast updates on submatrices by maintaining a difference matrix of the same size as the original matrix.
Suppose we have a 2D difference matrix \(\textit{diff}\), initially with all elements set to \(0\). For each query \([\textit{row1}, \textit{col1}, \textit{row2}, \textit{col2}]\), we can update the difference matrix through the following steps:
Increment position \((\textit{row1}, \textit{col1})\) by \(1\).
Decrement position \((\textit{row2} + 1, \textit{col1})\) by \(1\), provided that \(\textit{row2} + 1 < n\).
Decrement position \((\textit{row1}, \textit{col2} + 1)\) by \(1\), provided that \(\textit{col2} + 1 < n\).
Increment position \((\textit{row2} + 1, \textit{col2} + 1)\) by \(1\), provided that \(\textit{row2} + 1 < n\) and \(\textit{col2} + 1 < n\).
After completing all queries, we need to convert the difference matrix back to the original matrix using prefix sums. That is, for each position \((i, j)\), we calculate:
\[
\textit{mat}[i][j] = \textit{diff}[i][j] + (\textit{mat}[i-1][j] \text{ if } i > 0 \text{ else } 0) + (\textit{mat}[i][j-1] \text{ if } j > 0 \text{ else } 0) - (\textit{mat}[i-1][j-1] \text{ if } i > 0 \text{ and } j > 0 \text{ else } 0)
\]
The time complexity is \(O(m + n^2)\), where \(m\) and \(n\) are the length of \(\textit{queries}\) and the given \(n\), respectively. Ignoring the space consumed by the answer, the space complexity is \(O(1)\).