10. The Skyline Problem
A city's skyline is the outer contour of the silhouette formed by all the buildings when viewed from a distance. Given the positions and heights of all the buildings [left, right, height], return the key points that characterize the skyline.
How It Works & Algorithmic Design
Solves using Building Event Sorting + Active Max-Heap:
- Event Points: Split building
[L, R, H]into two boundary events:(L, -H)(start event) and(R, H)(end event). - Sort Events: Sort event points primarily by X-coordinate. For ties, sort start events before end events with higher heights first.
- Max-Heap & Max Height Track:
- Maintain
maxHeapof active building heights initialized with0. - For each event point
(x, h):- If start event (
h < 0), add $|h|$ to heap. - If end event (
h > 0), remove $h$ from heap. - Get
currentMax = maxHeap.peek(). - If
currentMax !== prevMax: contour height changed! Record key point[x, currentMax]and setprevMax = currentMax.
- If start event (
- Maintain
Why This Approach Works Best
Event sorting handles building overlaps cleanly, generating critical key points in $O(n \log n)$ time.
Example Walkthrough
[[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
Building bounds.
Height changes occur at x=2,3,7,9,12,15,20,24.
Outer silhouette contour.
[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
Skyline key points.
Answer: The Skyline Problem implementation
function getSkyline(buildings) {
const events = [];
for (const [l, r, h] of buildings) {
events.push([l, -h]);
events.push([r, h]);
}
events.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]);
const res = [];
const heights = [0];
let prevMax = 0;
for (const [x, h] of events) {
if (h < 0) {
heights.push(-h);
} else {
const idx = heights.indexOf(h);
if (idx !== -1) heights.splice(idx, 1);
}
heights.sort((a, b) => b - a);
const currentMax = heights[0];
if (currentMax !== prevMax) {
res.push([x, currentMax]);
prevMax = currentMax;
}
}
return res;
}Process building left and right edge sweep events using a Max-Heap to track silhouette contour changes.
Use negative height values to distinguish building start events from end events.
Record key point when active building height maximum changes.
Line sweep executes in $O(n \log n)$ time.