SDE & MLE Prep

218. The Skyline Problem

Problem

buildings[i] = [left, right, height] are rectangles standing on flat ground. Return the skyline (the outer contour of the union) as a list of key points [x, y] sorted by x: each marks the left end of a horizontal segment, and the last point has y = 0. Consecutive points must not have equal heights.

Example: [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]] → [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]

Constraints: up to 10⁴ buildings.

Sweep x-coordinates of all building edges. At each x, add buildings starting here to a max-heap of (height, right), lazily pop buildings whose right ≤ x. The skyline changes whenever the current max height differs from the last output height.

buildings [2,9,10] [3,7,15] [5,12,12] [15,20,10] [19,24,8]
x=2  heap {10}          max 10  -> (2,10)
x=3  heap {15,10}       max 15  -> (3,15)
x=7  15 expires         max 12  -> (7,12)
x=12 all expire         max 0   -> (12,0)   ... (15,10) (20,8) (24,0)

Complexity: O(n log n).

class Solution:
    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        xs = sorted({x for l, r, _ in buildings for x in (l, r)})
        res, h, i = [], [(0, float("inf"))], 0        # heap of (-height, right); ground never ends
        for x in xs:
            while i < len(buildings) and buildings[i][0] <= x:
                l, r, ht = buildings[i]
                heappush(h, (-ht, r))
                i += 1
            while h[0][1] <= x:
                heappop(h)
            top = -h[0][0]
            if not res or res[-1][1] != top:
                res.append([x, top])
        return res