1147. Stamp Coverage Count

Medium3.5 points estimatedPrefix SumMatrixCounting

A print shop stamps rectangular patterns onto an n x n sheet of paper. Each entry of rects is [r1, c1, r2, c2], the row and column of two opposite corners given in either order, so r1 may be larger than r2 and c1 larger than c2. A stamp adds one layer of ink to every cell of the rectangle between those corners, inclusive. After all stamps are applied, return how many cells have received at least t layers.

1 <= n <= 500, 1 <= rects.length <= 10^5, 0 <= r1, c1, r2, c2 < n and 1 <= t <= 10^5. Painting each rectangle cell by cell is too slow. Use a two-dimensional difference array with a two-dimensional prefix sum for O(n^2 + rects.length) time and O(n^2) space.

Example 1

Input:
n = 4, rects = [[0,0,1,1],[1,1,2,2]], t = 2
Output:
1
Explanation:

The two 2 x 2 stamps overlap only at cell (1, 1), so exactly one cell has two layers.

Example 2

Input:
n = 3, rects = [[2,2,0,0]], t = 1
Output:
9
Explanation:

The corners are given in reverse order, but the stamp still covers the whole 3 x 3 sheet, so 9 cells qualify.

Example 3

Input:
n = 2, rects = [[0,0,0,0],[1,1,1,1]], t = 2
Output:
0
Explanation:

No cell is stamped twice, so the answer is 0.

Constraints

1 ≤ n ≤ 500

1 ≤ rects.length ≤ 105

0 ≤ r1, c1, r2, c2 < n

1 ≤ t ≤ 105

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n^2 + q)
Space
O(n^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…