1386. Silhouette Area
A town planner photographs a row of warehouses from far away, so every warehouse looks like a flat rectangle standing on the ground line. Entry buildings[i] = [left, width, height] is the rectangle that spans the x range [left, left + width) and the y range [0, height). Rectangles may overlap or hide each other.
Return the area of the union of all rectangles, that is, the total area of the painted region when overlaps are counted only once, as a 64-bit integer.
Sweep the x boundaries from left to right while keeping the active rectangles in a max-heap ordered by height. Remove an expired top rectangle lazily when you meet it, and for each stretch between two consecutive boundaries add (current tallest active height) x (stretch width). The intended solution runs in O(n log n) time and O(n) space.
Example 1
- Input:
- buildings = [[1,3,4],[2,4,2],[8,2,5]]
- Output:
- 26
- Explanation:
The first two rectangles cover x in [1,4) with height 4 (area 12) and x in [4,6) with height 2 (area 4); the last adds 2 x 5 = 10, so the union is 26.
Example 2
- Input:
- buildings = [[5,2,3],[5,2,3]]
- Output:
- 6
- Explanation:
Two identical rectangles count once: 2 x 3 = 6.
Example 3
- Input:
- buildings = [[1,1,1]]
- Output:
- 1
- Explanation:
A single unit square has area 1.
Constraints
1 ≤ n (buildings.length) ≤ 105
buildings[i].length == 3
1 ≤ left, width, height ≤ 104
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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)