The Skyline Problem (LeetCode 218): Solution and Explanation
Each building is a rectangle given by its left edge, right edge and height, all standing on flat ground. Return the key points of the combined outline: each point where the height of the silhouette changes, listed from left to right.
Watch it run step by step
Try your own input and write the code →Intuition
A brute-force approach records, for every x coordinate that matters, the tallest building covering it, then emits a point wherever that height changes. Checking every building at every edge coordinate is O(n²), which is too slow for ten thousand buildings.
Sweep a vertical line from left to right instead. The outline can only change at a building edge, so those are the only events. At any moment, the visible height is the tallest building currently under the line. That calls for a max-heap of active buildings, and Python's min-heap works with negated heights. Each heap entry also stores the building's right edge, so you can tell when it has ended.
Removing a specific building from a heap is awkward, so the code uses lazy deletion. At each event, it pops from the top only while the tallest entry has already ended (end <= x). Buried expired buildings are harmless, because they cannot affect the answer until they reach the top, and at that point they are popped. A start event pushes the new building. Then, if the current tallest height differs from the last height in the output, the outline changed here and a key point is appended.
The sort order handles ties. Start events are (left, -height, right) and end events are (right, 0, 0). At the same x, a start sorts before an end because its middle value is negative, and among starts, taller buildings come first. That ordering prevents spurious points such as a dip to the ground where one building ends exactly as another begins.
Approach: Sweep line with a lazy max-heap
- Create a start event
(left, -height, right)and an end event(right, 0, 0)for every building, then sort all events. - Start
resultwith a dummy[0, 0]and the heap with a ground entry(0, inf)that never expires. - For each event at
x, pop heap entries while the top's right edge is at mostx. - If the event is a start (
neg_his non-zero), push(neg_h, end). - Read the current tallest height
-heap[0][0]. If it differs from the last height inresult, append[x, height]. - Return
result[1:]to drop the dummy point.
Step-by-step example
buildings = [[2,9,10],[3,7,15],[5,12,12]]
- Sorted events: starts at 2 (height 10), 3 (15), 5 (12), and ends at 7, 9 and 12.
- At x = 2, push height 10. The top is 10, which differs from 0, so add
[2,10]. At x = 3, push 15 and add[3,15]. - At x = 5, push 12. The top is still 15, so nothing is added.
- At x = 7, the 15 ends and is popped. The top becomes 12 (which ends at 12), so add
[7,12]. At x = 9, the top 12 is still active; the expired 10 is buried and ignored, so nothing changes. - At x = 12, pop the 12 and then the stale 10, leaving the ground at 0, so add
[12,0]. The result is[[2,10],[3,15],[7,12],[12,0]].
Code: Python, Java, C++
1class Solution:
2 def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
3 events = []
4 for left, right, height in buildings:
5 events.append((left, -height, right))
6 events.append((right, 0, 0))
7 events.sort()
8
9 result = [[0, 0]]
10 heap = [(0, float('inf'))] # (neg_height, end)
11
12 for x, neg_h, end in events:
13 while heap[0][1] <= x:
14 heapq.heappop(heap)
15
16 if neg_h:
17 heapq.heappush(heap, (neg_h, end))
18
19 if result[-1][1] != -heap[0][0]:
20 result.append([x, -heap[0][0]])
21
22 return result[1:]1class Solution {
2 public List<List<Integer>> getSkyline(int[][] buildings) {
3 List<int[]> events = new ArrayList<>();
4 for (int[] b : buildings) {
5 events.add(new int[]{b[0], -b[2], b[1]});
6 events.add(new int[]{b[1], 0, 0});
7 }
8 events.sort((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);
9
10 List<List<Integer>> result = new ArrayList<>();
11 result.add(Arrays.asList(0, 0));
12
13 PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
14 heap.offer(new int[]{0, Integer.MAX_VALUE});
15
16 for (int[] e : events) {
17 int x = e[0], negH = e[1], end = e[2];
18
19 while (heap.peek()[1] <= x) {
20 heap.poll();
21 }
22
23 if (negH != 0) {
24 heap.offer(new int[]{-negH, end});
25 }
26
27 int maxH = heap.peek()[0];
28 if (result.get(result.size() - 1).get(1) != maxH) {
29 result.add(Arrays.asList(x, maxH));
30 }
31 }
32
33 return result.subList(1, result.size());
34 }
35}1class Solution {
2public:
3 vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
4 vector<tuple<int, int, int>> events;
5 for (auto& b : buildings) {
6 events.push_back({b[0], -b[2], b[1]});
7 events.push_back({b[1], 0, 0});
8 }
9 sort(events.begin(), events.end());
10
11 vector<vector<int>> result = {{0, 0}};
12 priority_queue<pair<int, int>> heap;
13 heap.push({0, INT_MAX});
14
15 for (auto& [x, negH, end] : events) {
16 while (heap.top().second <= x) {
17 heap.pop();
18 }
19
20 if (negH) {
21 heap.push({-negH, end});
22 }
23
24 int maxH = heap.top().first;
25 if (result.back()[1] != maxH) {
26 result.push_back({x, maxH});
27 }
28 }
29
30 return vector<vector<int>>(result.begin() + 1, result.end());
31 }
32};Time and space complexity
O(n log n)
Sorting 2n events costs O(n log n). Each building is pushed once and popped at most once, and each heap operation is O(log n).
O(n)
The event list has 2n entries and the heap holds at most n buildings plus the ground entry.
Other approaches
Divide and conquer merge (time O(n log n), space O(n))
Split the buildings in half, compute each half's skyline recursively, then merge the two outlines like merge sort, tracking the current height of each side and taking the max.
Sorted multiset with removal (time O(n log n), space O(n))
Use a balanced tree or sorted container of active heights, removing a building's height exactly at its end event instead of lazily. The logic is simpler to reason about where an ordered multiset is available, as in C++ or Java.
Common mistakes
- Sorting end events before start events at the same x. A building ending at 5 and another starting at 5 would produce a false drop to the lower height followed by a jump back up.
- Emitting a point at every event instead of only when the maximum height changes, which yields duplicate heights in a row.
- Popping with
end < xinstead ofend <= x. A building's right edge is where it stops, so at that exact x it must no longer count. - Forgetting the ground entry, so the heap can become empty and reading
heap[0]raises an error after the last building ends.
Frequently asked questions
How does the sweep line solve the skyline problem?
It processes building edges from left to right while a heap tracks the buildings that currently cover the sweep line. Whenever the tallest active height changes, that x and height form a key point.
Why use lazy deletion in the heap?
Heaps cannot remove an arbitrary element efficiently. Leaving expired buildings in place and discarding them only when they reach the top keeps every operation O(log n).
What is the time complexity of the skyline problem?
O(n log n), from sorting the 2n events and performing O(n) heap operations.
Why are start heights stored as negative numbers?
Python's heapq is a min-heap, so negating heights makes the tallest building appear at the top. It also makes start events sort before end events at the same x, and taller starts first.