The Skyline Problem

Hard

Topics
ArraySweep LineHeapDivide and ConquerSegment Tree

You are given buildings where buildings[i] = [left, right, height] describes a rectangle standing on a flat ground line.

Return the skyline as a list of key points [x, height], sorted by x. A key point is the left endpoint of a horizontal segment of the outline. The last point always has height 0, marking where the skyline ends.

There must be no consecutive points of equal height — merge those segments.

Example 1

Buildings are drawn as overlapping blocks; the outline traced over them is the skyline. The answer is the list of corner points where that outline changes height — 7 of them here — which is why a height-ordered sweep across the x coordinates solves it.
One row per building: [left, right, height].
Input:  buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]

Example 2

Input:  buildings = [[0,2,3],[2,5,3]]
Output: [[0,3],[5,0]]
Explanation: The two buildings touch and are the same height, so the outline is one segment.

Constraints

  • 1 <= buildings.length <= 10^4
  • 0 <= left < right <= 2^31 - 1
  • 1 <= height <= 2^31 - 1
  • buildings is sorted by left ascending
Editorial — intuition, approach, complexity and pitfalls

Intuition

Sweep a vertical line left to right and track the tallest building currently covering it. The outline only changes where that maximum changes, which can only happen at a building's left or right edge. So gather all edges as events, keep the active heights in a multiset, and emit a key point whenever the running maximum differs from the last one emitted.

Approach

  1. Turn each building into two events: (left, -height) for a start and (right, 0) for an end. Sort events by x, and for ties by the second field — that puts taller starts before shorter starts, and all starts before ends at the same x.
  2. Keep a multiset (or a max-heap with lazy deletion) of active heights, seeded with 0 for ground level.
  3. At a start event, insert the height. At an end event, remove the height of the building that just finished.
  4. After processing every event at the current x, read the current maximum. If it differs from the previously emitted height, append [x, maxHeight].
  5. The tie-breaking rules are what make the "no two consecutive equal heights" requirement fall out automatically rather than needing a cleanup pass.
import heapq

class Solution:
    def getSkyline(self, buildings):
        events = []
        for left, right, height in buildings:
            events.append((left, -height, right))
            events.append((right, 0, 0))
        events.sort()

        result = []
        live = [(0, float("inf"))]
        for x, neg_h, right in events:
            while live[0][1] <= x:
                heapq.heappop(live)
            if neg_h:
                heapq.heappush(live, (neg_h, right))
            height = -live[0][0]
            if not result or result[-1][1] != height:
                result.append([x, height])
        return result

Dry Run

buildings = [2,9,10] [3,7,15] [5,12,12] [15,20,10] [19,24,8]

Each building becomes two events: (left, -height, right) and (right, 0, 0).
Sorted, with the negative height making a taller start sort first at the same x.
`active` is a heap of (-height, end), seeded with (0, inf) as the ground.

x=2   push (-10, 9)    active=[(-10,9) (0,inf)]           tallest 10  emit [2,10]
x=3   push (-15, 7)    active=[(-15,7) (0,inf) (-10,9)]   tallest 15  emit [3,15]
x=5   push (-12, 12)   active=[(-15,7) (-12,12) ...]      tallest 15  unchanged
x=7   expire (-15,7)   active=[(-12,12) (0,inf) (-10,9)]  tallest 12  emit [7,12]
x=9   nothing expires yet at the top                      tallest 12  unchanged
x=12  expire (-12,12) then (-10,9)   active=[(0,inf)]     tallest 0   emit [12,0]
x=15  push (-10, 20)   active=[(-10,20) (0,inf)]          tallest 10  emit [15,10]
x=19  push (-8, 24)    active=[(-10,20) (0,inf) (-8,24)]  tallest 10  unchanged
x=20  expire (-10,20)  active=[(-8,24) (0,inf)]           tallest 8   emit [20,8]
x=24  expire (-8,24)   active=[(0,inf)]                   tallest 0   emit [24,0]

answer 2 10 | 3 15 | 7 12 | 12 0 | 15 10 | 20 8 | 24 0

Two details carry the whole thing. Expiry is lazy -- nothing is removed when a
building ends, only when a dead entry reaches the top of the heap, which is why
x=9 does no work and x=12 pops twice. And the output is only appended when the
tallest height actually CHANGES, which is what suppresses x=5, x=9 and x=19
without any special-casing.

Complexity

  • Time — O(n log n) — sorting the events dominates; each is pushed and popped once.
  • Space — O(n) for the event list and the heap.

Common Pitfalls

  • The tie-break at equal x is the whole problem. Sorting starts by negated height puts the taller building first, which prevents a spurious short segment.
  • Process all events at the same x before emitting, or you produce duplicate points at one coordinate.
  • Compare against the last emitted height, not the previous event's height, to satisfy the no-consecutive-equal rule.
  • A binary heap cannot remove an arbitrary element. Use lazy deletion (store the right edge and discard expired tops) or an ordered multiset.
  • Seed the active set with height 0 so the final descent to ground level is emitted.

Full Solution — all languages

class Solution:
    def getSkyline(self, grid):
        events = []
        for left, right, height in grid:
            events.append((left, -height, right))
            events.append((right, 0, 0))
        events.sort()

        import heapq
        out = []
        active = [(0, float('inf'))]   # (-height, end)
        for x, negHeight, end in events:
            while active[0][1] <= x:
                heapq.heappop(active)
            if negHeight != 0:
                heapq.heappush(active, (negHeight, end))
            current = -active[0][0]
            if not out or out[-1][1] != current:
                out.append([x, current])
        return out
Asked at Zomato
SensAI
Beta
Tap the mic to stop voice mode