The Skyline Problem
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^40 <= left < right <= 2^31 - 11 <= height <= 2^31 - 1buildingsis sorted byleftin 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.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
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.
| Approach | Time | Space |
|---|---|---|
| Check every critical x | O(n²) | O(n) |
| Optimal (sweep line with a max-heap) | O(n log n) | O(n) |
1Check every critical x
O(n²)There are up to 2n critical x values and each one scans all n buildings.O(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.
- Collect every left and right edge in a sorted set.
- For each x: h = max height over buildings with left <= x < right (0 if none).
- 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;
}
}class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
xs = set()
for left, right, _ in buildings:
xs.add(left)
xs.add(right)
result = []
prev = 0
for x in sorted(xs):
h = 0
for left, right, height in buildings:
if left <= x < right:
h = max(h, height)
if h != prev:
result.append([x, h])
prev = h
return resultclass Solution {
public:
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
set<int> xs;
for (auto& b : buildings) {
xs.insert(b[0]);
xs.insert(b[1]);
}
vector<vector<int>> result;
int prev = 0;
for (int x : xs) {
int h = 0;
for (auto& b : buildings) {
if (b[0] <= x && x < b[1]) h = max(h, b[2]);
}
if (h != prev) {
result.push_back({x, h});
prev = h;
}
}
return result;
}
};function getSkyline(buildings) {
const set = new Set();
for (const b of buildings) {
set.add(b[0]);
set.add(b[1]);
}
const xs = [...set].sort((a, b) => a - b);
const result = [];
let prev = 0;
for (const x of xs) {
let h = 0;
for (const b of buildings) {
if (b[0] <= x && x < b[1]) h = Math.max(h, b[2]);
}
if (h !== prev) {
result.push([x, h]);
prev = h;
}
}
return result;
}2Optimal (sweep line with a max-heap)
O(n log n)Sorting 2n edges, and each building is pushed and popped at most once at O(log n) each.O(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.
- Put every left and right edge into an array xs and sort it.
- Keep a pointer i into buildings (already sorted by left) and a max-heap of [height, right].
- For each x: push every building with left <= x, then pop while the top's right <= x.
- 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;
}
}class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
n = len(buildings)
xs = []
for left, right, _ in buildings:
xs.append(left)
xs.append(right)
xs.sort()
heap = []
result = []
i = prev = 0
for x in xs:
while i < n and buildings[i][0] <= x:
heapq.heappush(heap, (-buildings[i][2], buildings[i][1]))
i += 1
while heap and heap[0][1] <= x:
heapq.heappop(heap)
h = -heap[0][0] if heap else 0
if h != prev:
result.append([x, h])
prev = h
return resultclass Solution {
public:
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
int n = buildings.size();
vector<int> xs;
for (auto& b : buildings) {
xs.push_back(b[0]);
xs.push_back(b[1]);
}
sort(xs.begin(), xs.end());
priority_queue<pair<int, int>> heap;
vector<vector<int>> result;
int i = 0, prev = 0;
for (int x : xs) {
while (i < n && buildings[i][0] <= x) {
heap.push({buildings[i][2], buildings[i][1]});
i++;
}
while (!heap.empty() && heap.top().second <= x) heap.pop();
int h = heap.empty() ? 0 : heap.top().first;
if (h != prev) {
result.push_back({x, h});
prev = h;
}
}
return result;
}
};class MinHeap {
constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
size() { return this.a.length; }
isEmpty() { return this.a.length === 0; }
peek() { return this.a[0]; }
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (this.cmp(a[i], a[p]) >= 0) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]];
i = m;
}
}
return top;
}
}
function getSkyline(buildings) {
const n = buildings.length;
const xs = [];
for (const b of buildings) {
xs.push(b[0]);
xs.push(b[1]);
}
xs.sort((a, b) => a - b);
const heap = new MinHeap((a, b) => b[0] - a[0]);
const result = [];
let i = 0, prev = 0;
for (const x of xs) {
while (i < n && buildings[i][0] <= x) {
heap.push([buildings[i][2], buildings[i][1]]);
i++;
}
while (!heap.isEmpty() && heap.peek()[1] <= x) heap.pop();
const h = heap.isEmpty() ? 0 : heap.peek()[0];
if (h !== prev) {
result.push([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.