Increment Submatrices by One
Problem
You are given a positive integer , indicating that we initially have an 0-indexed integer matrix filled with zeroes.
You are also given a 2D integer array . For each , you should do the following operation:
- Add to every element in the submatrix with the top left corner and the bottom right corner .
- That is, add to for for all and .
Return the matrix after performing every query.
Example
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.
Constraints
Submit your solution at here
Solution
Brute Force (TLE)
The brute force approach has complexity and very likely to TLE. But I heard some people managed to AC with it. I was not that lucky and got TLE.
class Solution {
public:
vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {
vector<vector<int>> ret(n, vector<int>(n, 0));
for(auto& q: queries) {
for(int i = q[0];i<=q[2];i++)
for(int j = q[1];j<=q[3];j++)
ret[i][j]++;
}
return ret;
}
};
Intuition
We will solve this row by row. On each row, we manage an array to keep track of how the value change. Let denotes that For each query that span from it will make and , everything in the middle would not change and stay as is. We can build the array in where is the . We also need a nested loop to update the array so the overall complexity would be
Complexity
- Time complexity:
- Space complexity:
Code
class Solution {
public:
vector<vector<int>> rangeAddQueries(int n, vector<vector<int>>& queries) {
vector<vector<int>> ret(n, vector<int>(n, 0));
vector<vector<int>> delta(n, vector<int>(n, 0));
for(auto& q: queries) {
int x0 = q[0], y0 = q[1], xn = q[2], yn = q[3];
for(int y = y0;y<=yn;y++) {
delta[x0][y]++;
if(xn+1 >= n) continue;
delta[xn+1][y]--;
}
}
for(int x = 0;x<n;x++) {
for(int y = 0;y<n;y++) {
auto prev = (x == 0?0:ret[x-1][y]);
ret[x][y] = prev + delta[x][y];
}
}
return ret;
}
};
FYI
I failed today’s contest 😭😭😭 There goes my rating.