1390. Buildings Seen in Outline

Hard7.5 points estimatedLine SweepHeapSortingOrdered Set

A photographer stands far away and looks at a row of buildings from the side. Building i is buildings[i] = [left, width, height] and fills the horizontal span from left up to but not including left + width at the given height. Buildings may overlap in span.

A building is visible if there is some stretch of positive length along the x axis over which it is strictly taller than every other building covering that stretch. If two buildings tie for the tallest on a stretch, neither is seen there. Each building is counted at most once. Return the number of visible buildings. With 10^5 buildings a scan of all buildings per stretch is too slow; aim for O(n log n) time and O(n) space.

Example 1

Input:
buildings = [[1,4,3],[2,2,5]]
Output:
2
Explanation:

The first building is the tallest on [1, 2) and [4, 5), and the second tower rises above it on [2, 4), so both are seen.

Example 2

Input:
buildings = [[1,3,4],[1,3,4]]
Output:
0
Explanation:

The two buildings are identical, so they tie on every stretch and neither is ever strictly tallest.

Example 3

Input:
buildings = [[1,5,2],[2,3,2],[3,1,7]]
Output:
2
Explanation:

The first two tie at height 2 wherever both are present, so only the first (on [1, 2) and [5, 6)) and the tall third building are seen.

Constraints

1 ≤ n ≤ 105; 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 4,800 msC++ 1,200 msJava 2,400 msJavaScript 2,400 msTypeScript 2,400 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…