Problem Statement in English
You’re given an integer n and a 2D array queries where each queries[i] = [topLeftRow, topLeftCol, bottomRightRow, bottomRightCol] represents a submatrix of an n x n matrix.
Initially, the matrix is filled with all zeros.
Your task is to increment all the elements of each submatrix defined by the queries by one and return the resulting matrix.
Approach
I went for the slightly less efficient but straightforward approach that only uses a difference array for each row. But you could also use a 2D difference array to achieve the same result with slightly better time complexity. Albeit, a little more complex to implement.
The idea is that for each query, we iterate through the rows of the submatrix defined by the query and update the difference array for that row. Specifically, we increment the value at the topLeftCol index and decrement the value at the bottomRightCol + 1 index (if it exists). So it’s just 2 operations per row per query.
I noticed that there are at most queries, and n can be at most 500. So in the worst case, we would be doing operations which is acceptable.
But if the constraints were larger, we could have used a 2D difference array and ended up with better time complexity.
Solution in Python
class Solution:
def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:
diffMatrix = [[0 for _ in range(n)] for _ in range(n)]
for tlr, tlc, brr, brc in queries:
for row in range(tlr, min(n, brr + 1)):
diffMatrix[row][tlc] += 1
if brc + 1 >= n:
continue
diffMatrix[row][brc + 1] -= 1
resMatrix = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
acc = 0
for j in range(n):
acc += diffMatrix[i][j]
resMatrix[i][j] = acc
return resMatrix
Complexity
Time:
Since we process q queries in time and then build the result matrix in time.Space:
And we are done.