The Skyline Problem

Hard Heaps Advanced

The Skyline Problem is a hard heaps problem solved with the advanced pattern. The best approach, optimal (sweep line with a max-heap), runs in O(n log n) time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from check every critical x up.

Problem

A city is drawn as a row of flat-topped rectangles standing on the ground (height 0). Each building is given as [left, right, height]: it covers every x from left up to right and rises to height. Buildings may overlap or touch.

Return the skyline: the outline you would see from far away, written as a list of key points [x, height] sorted by x. A key point marks the spot where the outline changes to a new height, and that height holds until the next key point. The last key point always has height 0, where the rightmost building ends. Two consecutive key points must never have the same height: a flat stretch is described by a single key point.

Examples

Example 1

Input
buildings = [[1, 4, 3], [2, 6, 5], [5, 8, 2]]
Output
[[1, 3], [2, 5], [6, 2], [8, 0]]
Why
The outline rises to 3 at x = 1 and to 5 at x = 2. The tall building hides the end of the first one at x = 4 and the start of the third at x = 5. When it ends at x = 6 the outline drops to 2, and it reaches the ground at x = 8.

Example 2

Input
buildings = [[0, 3, 4], [3, 5, 4]]
Output
[[0, 4], [5, 0]]
Why
The two buildings touch at x = 3 and have the same height, so the outline is one flat roof of height 4 from 0 to 5. No key point is written at x = 3 because the height does not change there.

Example 3

Input
buildings = [[1, 2, 1], [4, 6, 2]]
Output
[[1, 1], [2, 0], [4, 2], [6, 0]]
Why
There is a gap between the buildings, so the outline returns to height 0 at x = 2 before rising again at x = 4.

Constraints

  • 1 <= buildings.length <= 10^4
  • 0 <= left < right <= 2^31 - 1
  • 1 <= height <= 2^31 - 1
  • buildings is sorted by left in non-decreasing order.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Check every critical xO(n²)O(n)
Optimal (sweep line with a max-heap)O(n log n)O(n)

1Check every critical x

TimeO(n²)There are up to 2n critical x values and each one scans all n buildings.
SpaceO(n)The set of critical x values and the output.

Only the left and right edges of buildings can change the outline. For each such x in increasing order, scan all buildings to find the tallest one covering x, and write a key point whenever that height differs from the previous one.

  1. Collect every left and right edge in a sorted set.
  2. For each x: h = max height over buildings with left <= x < right (0 if none).
  3. If h differs from the previous height, append [x, h] and remember h.
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]);
        }
        List<List<Integer>> result = new ArrayList<>();
        int prev = 0;
        for (int x : xs) {
            int h = 0;
            for (int[] b : buildings) {
                if (b[0] <= x && x < b[1]) h = Math.max(h, b[2]);
            }
            if (h != prev) {
                result.add(Arrays.asList(x, h));
                prev = h;
            }
        }
        return result;
    }
}

2Optimal (sweep line with a max-heap)

TimeO(n log n)Sorting 2n edges, and each building is pushed and popped at most once at O(log n) each.
SpaceO(n)The edge array and the heap hold O(n) items.

Sweep the sorted edges from left to right. Push every building that has started into a max-heap keyed by height, storing its right edge too. Before reading the height, pop the top while its building has already ended at or before x. Buildings that ended but sit lower in the heap can stay there: they are only removed when they reach the top. The top that remains is the outline height at x.

  1. Put every left and right edge into an array xs and sort it.
  2. Keep a pointer i into buildings (already sorted by left) and a max-heap of [height, right].
  3. For each x: push every building with left <= x, then pop while the top's right <= x.
  4. h = top height, or 0 if the heap is empty. If h differs from the previous height, append [x, h].
class Solution {
    public List<List<Integer>> getSkyline(int[][] buildings) {
        int n = buildings.length;
        int[] xs = new int[2 * n];
        for (int k = 0; k < n; k++) {
            xs[2 * k] = buildings[k][0];
            xs[2 * k + 1] = buildings[k][1];
        }
        Arrays.sort(xs);
        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(b[0], a[0]));
        List<List<Integer>> result = new ArrayList<>();
        int i = 0, prev = 0;
        for (int x : xs) {
            while (i < n && buildings[i][0] <= x) {
                heap.offer(new int[]{buildings[i][2], buildings[i][1]});
                i++;
            }
            while (!heap.isEmpty() && heap.peek()[1] <= x) heap.poll();
            int h = heap.isEmpty() ? 0 : heap.peek()[0];
            if (h != prev) {
                result.add(Arrays.asList(x, h));
                prev = h;
            }
        }
        return result;
    }
}

Edge cases to test

  • A single building (two key points)
  • Buildings that touch with the same height (no key point where they meet)
  • A short building completely hidden inside a taller one
  • Gaps between buildings (the outline drops to 0)
  • Several buildings starting or ending at the same x

Hints

Hint 1

The outline can only change height at an x where some building starts or ends.

Hint 2

At such an x, the height of the outline is the tallest building that covers it, where a building covers x when left <= x < right.

Hint 3

Sweep the critical x values from left to right and keep the buildings that have started in a max-heap by height. Throw away the top while it has already ended; the top that remains is the current height.

FAQ

What is the best time complexity for The Skyline Problem?

Optimal (sweep line with a max-heap) runs in O(n log n) time and O(n) extra space. Sorting 2n edges, and each building is pushed and popped at most once at O(log n) each.

Which pattern does The Skyline Problem use?

It is a heaps problem that uses the advanced pattern. Other problems with the same pattern: Find K Pairs with Smallest Sums, Find Median from Data Stream, Trapping Rain Water II.

Is there a brute force solution for The Skyline Problem?

Yes. Check every critical x takes O(n²) time and O(n) space. Only the left and right edges of buildings can change the outline.

Which edge cases should I test for The Skyline Problem?

A single building (two key points); Buildings that touch with the same height (no key point where they meet); A short building completely hidden inside a taller one; Gaps between buildings (the outline drops to 0); Several buildings starting or ending at the same x.