1420. Overlapping Sheet Pairs

A sign painter has cut many rectangular sheets of vinyl. Sheet i is rects[i] = [x, y, w, h] and covers the half-open region from x up to but not including x + w, and from y up to but not including y + h. Sheets that merely touch along an edge or at a corner do not overlap.

Return the number of unordered pairs of sheets that share a region of positive area, as a 64-bit integer. Identical sheets form a pair with each other. Right edges and top edges can reach 2 * 10^9, which does not fit in a signed 32-bit integer, so use 64-bit arithmetic for coordinates as well as for the count. With 10^5 sheets a pairwise check is too slow; aim for O(n log n) time and O(n) space.

Example 1

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

The sheets share the unit square from (1, 1) to (2, 2), so the one pair overlaps.

Example 2

Input:
rects = [[0,0,2,2],[2,0,2,2]]
Output:
0
Explanation:

The sheets only touch along the line x = 2, which has no area, so the answer is 0.

Example 3

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

The big first sheet overlaps both others, while the small one and the third sheet only meet at a corner, giving 2 pairs.

Constraints

1 ≤ n ≤ 105; 0 ≤ x, y ≤ 109; 1 ≤ w, h ≤ 109. The answer fits in a 64-bit integer.

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 8,000 msC++ 2,000 msJava 4,000 msJavaScript 4,000 msTypeScript 4,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

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…