Katkat

Count Rectangle Coverage on a Grid

GoogleSoftware Engineer · Onsite

Last updated

Implement an algorithm to compute cell-by-cell coverage counts for an n x n grid given multiple inclusive rectangular regions.

Problem Statement

Given an integer n representing the dimensions of an n x n 2D grid initialized to all zeros, and an array of rectangles rectangles, return the final grid where each cell (r, c) contains the number of rectangles covering that cell.

Each rectangle is represented as a 4-element list [r1, c1, r2, c2], indicating the top-left coordinate (r1, c1) and the bottom-right coordinate (r2, c2) inclusive. A cell (r, c) is covered by a rectangle if r1 <= r <= r2 and c1 <= c <= c2.

Your solution should be non-mutating (do not modify the input list of rectangles) and must handle large numbers of updates efficiently.

Function Signature

def count_coverage(n: int, rectangles: list[list[int]]) -> list[list[int]]:
    pass

Constraints

  • 1 <= n <= 1000
  • 0 <= len(rectangles) <= 10^5
  • rectangles[i] has length 4
  • 0 <= r1 <= r2 < n
  • 0 <= c1 <= c2 < n

Examples

Example 1

Input: n = 3, rectangles = [[0, 0, 1, 1], [1, 1, 2, 2]]
Output:
[
  [1, 1, 0],
  [1, 2, 1],
  [0, 1, 1]
]
Explanation:
- The first rectangle covers (0,0), (0,1), (1,0), (1,1).
- The second rectangle covers (1,1), (1,2), (2,1), (2,2).
- Cell (1, 1) is overlapped by both rectangles, yielding a count of 2.

Example 2

Input: n = 2, rectangles = []
Output:
[
  [0, 0],
  [0, 0]
]
Explanation: No rectangles are provided, so every cell retains a coverage count of 0.

Edge Cases

  • rectangles is empty (len(rectangles) == 0).
  • Single-cell rectangles where r1 == r2 and c1 == c2.
  • Full-grid coverage where [r1, c1, r2, c2] = [0, 0, n - 1, n - 1].
  • Duplicate rectangle entries in rectangles (each duplicate must contribute to the count independently).

Hints

Hint 1

A direct simulation updating every cell inside each rectangle takes O(k * n^2) time, which will be too slow for large inputs.

Hint 2

Consider extending the 1D difference array technique to 2D by marking four corners for each rectangle in O(1) time.

Hint 3

After marking all rectangle boundaries on an auxiliary (n+1) x (n+1) difference grid, compute a 2D prefix sum to obtain the final counts in O(n^2) total time.

Follow-up questions

  • How would your approach change if n was up to 10^9, but k <= 1000 and you only needed to return the total area covered by at least one rectangle?
  • If the problem required handling frequent point-lookup queries interspersed with rectangle additions, what data structure would you use?
  • How can you optimize space if memory is constrained and you are only allowed to output rows one at a time via a generator?