218. The Skyline Problem
Asked at 12Microsoft39Meta32Google30Apple22Amazon22Bloomberg14Yelp94X94Zomato81Siemens75Goldman Sachs36Uber22
Problem
buildings[i] = [left, right, height] are rectangles standing on flat ground. Return the skyline (the outer contour of the union) as a list of key points [x, y] sorted by x: each marks the left end of a horizontal segment, and the last point has y = 0. Consecutive points must not have equal heights.
Example: [[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: up to 10⁴ buildings.
Sweep x-coordinates of all building edges. At each x, add buildings starting here to a max-heap of (height, right), lazily pop buildings whose right ≤ x. The skyline changes whenever the current max height differs from the last output height.
buildings [2,9,10] [3,7,15] [5,12,12] [15,20,10] [19,24,8]
x=2 heap {10} max 10 -> (2,10)
x=3 heap {15,10} max 15 -> (3,15)
x=7 15 expires max 12 -> (7,12)
x=12 all expire max 0 -> (12,0) ... (15,10) (20,8) (24,0)
Complexity: O(n log n).
class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
xs = sorted({x for l, r, _ in buildings for x in (l, r)})
res, h, i = [], [(0, float("inf"))], 0 # heap of (-height, right); ground never ends
for x in xs:
while i < len(buildings) and buildings[i][0] <= x:
l, r, ht = buildings[i]
heappush(h, (-ht, r))
i += 1
while h[0][1] <= x:
heappop(h)
top = -h[0][0]
if not res or res[-1][1] != top:
res.append([x, top])
return res
B = [[2, 9, 10], [3, 7, 15], [5, 12, 12], [15, 20, 10], [19, 24, 8]]
assert Solution().getSkyline(B) == [[2, 10], [3, 15], [7, 12], [12, 0], [15, 10], [20, 8], [24, 0]]
assert Solution().getSkyline([[0, 2, 3], [2, 5, 3]]) == [[0, 3], [5, 0]]
class Solution {
public List<List<Integer>> getSkyline(int[][] buildings) {
TreeSet<Integer> xs = new TreeSet<>();
for (int[] b : buildings) { xs.add(b[0]); xs.add(b[1]); }
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]); // {height, right}
pq.add(new int[]{0, Integer.MAX_VALUE});
List<List<Integer>> res = new ArrayList<>();
int i = 0;
for (int x : xs) {
while (i < buildings.length && buildings[i][0] <= x) { pq.add(new int[]{buildings[i][2], buildings[i][1]}); i++; }
while (pq.peek()[1] <= x) pq.poll();
int top = pq.peek()[0];
if (res.isEmpty() || res.get(res.size() - 1).get(1) != top) res.add(List.of(x, top));
}
return res;
}
}
type heightHeap [][2]int // (height, right edge), tallest first
func (h heightHeap) Len() int { return len(h) }
func (h heightHeap) Less(i, j int) bool { return h[i][0] > h[j][0] }
func (h heightHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *heightHeap) Push(x any) { *h = append(*h, x.([2]int)) }
func (h *heightHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func getSkyline(buildings [][]int) [][]int {
xs := []int{} // every edge is a candidate key point
for _, b := range buildings {
xs = append(xs, b[0], b[1])
}
sort.Ints(xs)
res := [][]int{}
h := &heightHeap{{0, math.MaxInt}} // the ground never ends
i := 0
for k, x := range xs {
if k > 0 && x == xs[k-1] {
continue
}
for ; i < len(buildings) && buildings[i][0] <= x; i++ { // buildings started by x
heap.Push(h, [2]int{buildings[i][2], buildings[i][1]})
}
for (*h)[0][1] <= x { // lazily drop the tallest while it has ended
heap.Pop(h)
}
if top := (*h)[0][0]; len(res) == 0 || res[len(res)-1][1] != top {
res = append(res, []int{x, top})
}
}
return res
}