The Skyline Problem
Hard
Topics
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
[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
- Turn each building into two events:
(left, -height)for a start and(right, 0)for an end. Sort events byx, and for ties by the second field — that puts taller starts before shorter starts, and all starts before ends at the samex. - Keep a multiset (or a max-heap with lazy deletion) of active heights, seeded with 0 for ground level.
- At a start event, insert the height. At an end event, remove the height of the building that just finished.
- After processing every event at the current
x, read the current maximum. If it differs from the previously emitted height, append[x, maxHeight]. - 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 resultDry 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
xis 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
xbefore 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 outimport java.util.*;
class Solution {
public int[][] getSkyline(int[][] grid) {
List<long[]> events = new ArrayList<>();
for (int[] b : grid) {
events.add(new long[]{b[0], -b[2], b[1]});
events.add(new long[]{b[1], 0, 0});
}
events.sort((p, q) -> {
if (p[0] != q[0]) return Long.compare(p[0], q[0]); if (p[1] != q[1]) return Long.compare(p[1], q[1]); return Long.compare(p[2], q[2]);
})
;
PriorityQueue<long[]> active = new PriorityQueue<>((p, q) -> p[0] != q[0] ? Long.compare(p[0], q[0]) : Long.compare(p[1], q[1]));
active.add(new long[]{0, Long.MAX_VALUE});
List<int[]> out = new ArrayList<>();
for (long[] e : events) {
long x = e[0];
while (active.peek()[1] <= x) active.poll();
if (e[1] != 0) active.add(new long[]{e[1], e[2]});
int current = (int) -active.peek()[0];
if (out.isEmpty() || out.get(out.size() - 1)[1] != current) {
out.add(new int[]{(int) x, current});
}
}
return out.toArray(new int[0][]);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> getSkyline(vector<vector<int>>& grid) {
vector<array<long long, 3>> events;
for (auto& b : grid) {
events.push_back({b[0], -(long long)b[2], b[1]});
events.push_back({b[1], 0, 0});
}
sort(events.begin(), events.end());
priority_queue<pair<long long, long long>, vector<pair<long long, long long>>, greater<pair<long long, long long>>> active;
active.push({0, LLONG_MAX});
vector<vector<int>> out;
for (auto& e : events) {
long long x = e[0];
while (active.top().second <= x) active.pop();
if (e[1] != 0) active.push({e[1], e[2]});
int current = (int)(-active.top().first);
if (out.empty() || out.back()[1] != current) out.push_back({(int)x, current});
}
return out;
}
};/**
* @param {number[][]} grid
* @return {number[][]}
*/ var getSkyline = function(grid) {
const events = [];
for (const b of grid) {
events.push([b[0], -b[2], b[1]]);
events.push([b[1], 0, 0]);
}
events.sort((p, q) => p[0] - q[0] || p[1] - q[1] || p[2] - q[2]);
// Kept-sorted active list in place of a heap; small inputs here.
const active = [[0, Infinity]];
const out = [];
for (const e of events) {
const x = e[0];
for (let i = active.length - 1; i >= 0; i--) if (active[i][1] <= x) active.splice(i, 1);
if (e[1] !== 0) {
let at = 0;
while (at < active.length && active[at][0] < e[1]) at++;
active.splice(at, 0, [e[1], e[2]]);
}
const current = -active[0][0];
if (!out.length || out[out.length - 1][1] !== current) out.push([x, current]);
}
return out;
};