Count Rectangle Coverage on a Grid
You are given an n x n grid initially filled with zeroes and a list of inclusive rectangular updates. Each rectangle adds one to every covered cell.
Implement:
range_add_counts(n, rectangles) -> list[list[int]]
Each rectangle is [row1, col1, row2, col2], using zero-based inclusive coordinates. Return the final grid, where each cell contains the number of rectangles covering it.
Example
n = 3
rectangles = [
[0, 0, 1, 1],
[1, 1, 2, 2]
]
result = [
[1, 1, 0],
[1, 2, 1],
[0, 1, 1]
]
Cell (1, 1) is covered by both rectangles.
Constraints
-
1 <= n <= 500
-
0 <= len(rectangles) <= 100000
-
0 <= row1 <= row2 < n
-
0 <= col1 <= col2 < n
-
Duplicate rectangles count as separate updates.
-
If
rectangles
is empty, return an all-zero grid.
Clarifications
-
Both lower and upper rectangle coordinates are included.
-
The input list must not be mutated.
-
Returning a newly allocated matrix is expected.
Hints
-
Updating every cell of every rectangle is too slow at the upper bound.
-
A two-dimensional difference array can encode a rectangle with four boundary changes.
-
Recover cell values by taking prefix sums across both dimensions, taking care at the grid edges.
Discussion Extensions
-
Derive the time and space complexity.
-
How would you adapt the method if coordinates were very large but only a small number of points were queried?
-
How would the boundary updates change for half-open rectangles?