The Skyline Problem

Compute the contour of building rectangles using a max-heap sweep over critical x-coordinates.

Hard
Time O(N log N) Space O(N)
LeetCode
7 min read
sweep-line heap sorting

Problem#

Given buildings as [left, right, height] triples, return the skyline as a sequence of [x, height] key-points marking each change in the contour.

Examples#

  • [[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#

  • 1 <= buildings.length <= 10^4.

Hints#

Hint 1
Create events at each building’s left and right edges; process in x order.
Hint 2
Maintain a max-heap of active heights; emit a key-point whenever the max changes.

Approach#

Sweep line. For each building, push (L, -H) (start, negative so starts process first/highest first) and (R, H) (end). Process events sorted by x; maintain a multiset of active heights. After each event group at the same x, if the current max height differs from previous, emit [x, currentMax].

Solution#

The Skyline Problem
class Solution {
public:
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
vector<pair<int,int>> events;
for (auto& b : buildings) {
events.emplace_back(b[0], -b[2]); // start (negative height)
events.emplace_back(b[1], b[2]); // end
}
sort(events.begin(), events.end());
multiset<int> heights;
heights.insert(0);
int prev = 0;
vector<vector<int>> ans;
for (auto& [x, h] : events) {
if (h < 0) heights.insert(-h);
else heights.erase(heights.find(h));
int cur = *heights.rbegin();
if (cur != prev) {
ans.push_back({x, cur});
prev = cur;
}
}
return ans;
}
};

Editorial#

Events sort by x, then by signed height — ascending signed height puts negatives (starts) before positives (ends), and within starts puts the taller building first (more negative = sorts earlier). This handles ties correctly: two buildings starting at the same x register the taller’s start first, and a start at the same x as another’s end registers the start first (preventing a spurious dip to zero).

Complexity#

  • Time: O(N log N).
  • Space: O(N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.