218. The Skyline Problem
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the skyline of a city, which is the outer contour formed by a set of rectangular buildings. We are given the dimensions [left, right, height] for each building. The skyline is to be represented as a list of "key points" [x, y], where each point is the left endpoint of a horizontal segment of the skyline. The output must be sorted by x-coordinate and must not have consecutive horizontal lines of the same height.
Solution
The Skyline Problem in Python
import heapq
from collections import Counter
class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
points = []
for l, r, h in buildings:
points.append((l, -h))
points.append((r, h))
points.sort()
skyline = []
# Max-heap implemented with min-heap storing negative heights
live_hr = [0]
# Counter for lazy removal
deleted = Counter()
last_max_h = 0
for x, h in points:
if h < 0: # left edge
heapq.heappush(live_hr, h)
else: # right edge
deleted[h] += 1
# Clean up the heap top from deleted heights
while live_hr and deleted[-live_hr[0]] > 0:
deleted[-live_hr[0]] -= 1
heapq.heappop(live_hr)
current_max_h = -live_hr[0]
if current_max_h != last_max_h:
if skyline and skyline[-1][0] == x:
skyline[-1][1] = current_max_h
else:
skyline.append([x, current_max_h])
last_max_h = current_max_h
# Final post-processing to merge points
res = []
if not skyline:
return res
res.append(skyline[0])
for i in range(1, len(skyline)):
if res[-1][1] == skyline[i][1]:
continue
if res[-1][0] == skyline[i][0]:
res[-1][1] = skyline[i][1]
# If this merge makes it redundant with the one before, pop the previous one
if len(res) >= 2 and res[-2][1] == res[-1][1]:
res[-2] = res[-1]
res.pop()
continue
res.append(skyline[i])
return res
The Skyline Problem in Java
class Solution {
public List<List<Integer>> getSkyline(int[][] buildings) {
// Create a list of critical points.
// A left edge is stored as [left, -height], a right edge as [right, height].
List<int[]> points = new ArrayList<>();
for (int[] b : buildings) {
points.add(new int[]{b[0], -b[2]});
points.add(new int[]{b[1], b[2]});
}
// Sort the critical points.
// Primary key: x-coordinate. Secondary key: y-coordinate (signed height).
Collections.sort(points, (a, b) -> {
if (a[0] != b[0]) {
return a[0] - b[0];
} else {
return a[1] - b[1];
}
});
// Use a TreeMap to maintain active heights and their counts.
// Keys are heights, values are frequencies.
TreeMap<Integer, Integer> active_heights = new TreeMap<>();
active_heights.put(0, 1); // Start with ground level.
List<List<Integer>> skyline = new ArrayList<>();
int last_max_height = 0;
// Sweep through the sorted points.
for (int[] p : points) {
int x = p[0];
int h = p[1];
if (h < 0) { // Left edge: a new building starts.
active_heights.put(-h, active_heights.getOrDefault(-h, 0) + 1);
} else { // Right edge: a building ends.
active_heights.put(h, active_heights.get(h) - 1);
if (active_heights.get(h) == 0) {
active_heights.remove(h);
}
}
// Get the current maximum height from the TreeMap.
int current_max_height = active_heights.lastKey();
// If the max height changes, we have a new key point.
if (current_max_height != last_max_height) {
skyline.add(Arrays.asList(x, current_max_height));
last_max_height = current_max_height;
}
}
// Post-processing to merge consecutive horizontal lines.
// Example: [[2,10], [3,10]] should be [[2,10]].
List<List<Integer>> merged_skyline = new ArrayList<>();
if (skyline.isEmpty()) return merged_skyline;
for (int i = 0; i < skyline.size(); i++) {
int current_x = skyline.get(i).get(0);
int current_y = skyline.get(i).get(1);
if (merged_skyline.isEmpty() || !merged_skyline.get(merged_skyline.size() - 1).get(1).equals(current_y)) {
// If current point has same x as last in result, update last point's y
if (!merged_skyline.isEmpty() && merged_skyline.get(merged_skyline.size() - 1).get(0).equals(current_x)) {
merged_skyline.get(merged_skyline.size() - 1).set(1, current_y);
} else {
merged_skyline.add(Arrays.asList(current_x, current_y));
}
}
}
return merged_skyline;
}
}
The Skyline Problem in C++
class Solution {
public:
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
// Create a list of critical points.
// A left edge is stored as {left, -height}, a right edge as {right, height}.
// The negative height for left edges helps in sorting and identifying edge types.
vector<pair<int, int>> points;
for (const auto& b : buildings) {
points.push_back({b[0], -b[2]});
points.push_back({b[1], b[2]});
}
// Sort the critical points. The primary key is the x-coordinate.
// The secondary key is the y-coordinate (the signed height).
// This ensures left edges are processed before right edges at the same x,
// and taller buildings are processed before shorter ones for left edges.
sort(points.begin(), points.end());
// Use a multiset to maintain the heights of active buildings.
// A multiset is a balanced binary search tree, allowing efficient add, remove, and find max.
multiset<int> active_heights = {0}; // Start with ground level.
vector<vector<int>> skyline;
int last_max_height = 0;
// Sweep through the sorted points.
for (const auto& p : points) {
int x = p.first;
int h = p.second;
if (h < 0) { // Left edge: a new building starts.
active_heights.insert(-h);
} else { // Right edge: a building ends.
// Important: erase only one instance of the height.
active_heights.erase(active_heights.find(h));
}
// Get the current maximum height from the multiset.
int current_max_height = *active_heights.rbegin();
// If the max height changes, we have a new key point for the skyline.
if (current_max_height != last_max_height) {
// If the skyline is not empty and the new point has the same x as the last one,
// it means multiple events happened at this x. We update the last point's height.
if (!skyline.empty() && skyline.back()[0] == x) {
skyline.back()[1] = current_max_height;
} else {
skyline.push_back({x, current_max_height});
}
// After adding/updating, check if the new point makes the previous one redundant (same height).
// e.g., we had [..., [1,5]] and now add [3,5]. The [1,5] is part of a longer horizontal line.
// But if we had [..., [1,0], [3,5]], then [1,0] is needed.
// This logic simplifies to removing points that become redundant vertically or horizontally.
// A simpler approach is to add and then clean up.
last_max_height = current_max_height;
}
}
// Post-processing to merge consecutive horizontal lines of the same height.
// For example, [[2, 5], [4, 5]] should be [[2, 5]].
vector<vector<int>> merged_skyline;
if (skyline.empty()) return merged_skyline;
merged_skyline.push_back(skyline[0]);
for (size_t i = 1; i < skyline.size(); ++i) {
if (skyline[i][1] != merged_skyline.back()[1]) {
// If new point has same x as last, it's a vertical line, update height of last point
if (skyline[i][0] == merged_skyline.back()[0]) {
merged_skyline.back()[1] = skyline[i][1];
} else {
merged_skyline.push_back(skyline[i]);
}
}
}
return merged_skyline;
}
};
The Skyline Problem in TypeScript
class PriorityQueue<T> {
private heap: T[];
private comparator: (a: T, b: T) => number;
constructor(comparator: (a: T, b: T) => number = (a, b) => a < b ? -1 : 1) {
this.heap = [];
this.comparator = comparator;
}
size(): number {
return this.heap.length;
}
isEmpty(): boolean {
return this.size() === 0;
}
peek(): T | undefined {
return this.heap[0];
}
push(value: T): void {
this.heap.push(value);
this.siftUp();
}
pop(): T | undefined {
if (this.isEmpty()) {
return undefined;
}
this.swap(0, this.size() - 1);
const value = this.heap.pop();
this.siftDown();
return value;
}
private parent(i: number): number { return Math.floor((i - 1) / 2); }
private leftChild(i: number): number { return 2 * i + 1; }
private rightChild(i: number): number { return 2 * i + 2; }
private swap(i: number, j: number): void { [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; }
private siftUp(): void {
let node = this.size() - 1;
while (node > 0 && this.comparator(this.heap[node], this.heap[this.parent(node)]) < 0) {
this.swap(node, this.parent(node));
node = this.parent(node);
}
}
private siftDown(): void {
let node = 0;
while (
(this.leftChild(node) < this.size() && this.comparator(this.heap[this.leftChild(node)], this.heap[node]) < 0) ||
(this.rightChild(node) < this.size() && this.comparator(this.heap[this.rightChild(node)], this.heap[node]) < 0)
) {
let maxChild = (this.rightChild(node) < this.size() && this.comparator(this.heap[this.rightChild(node)], this.heap[this.leftChild(node)]) < 0)
? this.rightChild(node)
: this.leftChild(node);
this.swap(node, maxChild);
node = maxChild;
}
}
}
function getSkyline(buildings: number[][]): number[][] {
// Create critical points: [x, height]. Left edges have negative height.
const points: number[][] = [];
for (const [left, right, height] of buildings) {
points.push([left, -height]);
points.push([right, height]);
}
// Sort points by x, then by height.
points.sort((a, b) => {
if (a[0] !== b[0]) {
return a[0] - b[0];
}
return a[1] - b[1];
});
// Max-heap to store active building heights.
const activeHeights = new PriorityQueue<number>((a, b) => b - a); // Max-heap
activeHeights.push(0); // Start with ground level
const heightCounts = new Map<number, number>(); // For lazy removal
heightCounts.set(0, 1);
let lastMaxHeight = 0;
const skyline: number[][] = [];
for (const [x, h] of points) {
if (h < 0) { // Left edge
const height = -h;
activeHeights.push(height);
heightCounts.set(height, (heightCounts.get(height) || 0) + 1);
} else { // Right edge
const height = h;
heightCounts.set(height, (heightCounts.get(height) || 0) - 1);
}
// Lazy removal: clean up top of the heap
while (!activeHeights.isEmpty() && (heightCounts.get(activeHeights.peek()!) || 0) === 0) {
activeHeights.pop();
}
const currentMaxHeight = activeHeights.peek() || 0;
if (currentMaxHeight !== lastMaxHeight) {
if (skyline.length > 0 && skyline[skyline.length - 1][0] === x) {
skyline[skyline.length - 1][1] = currentMaxHeight;
} else {
skyline.push([x, currentMaxHeight]);
}
lastMaxHeight = currentMaxHeight;
}
}
// Post-processing to merge redundant points.
const result: number[][] = [];
if (skyline.length === 0) return result;
result.push(skyline[0]);
for (let i = 1; i < skyline.length; i++) {
const last = result[result.length - 1];
const current = skyline[i];
if (last[1] === current[1]) continue; // same height, horizontal merge
if (last[0] === current[0]) { // same x, vertical merge
last[1] = current[1];
if (result.length >= 2 && result[result.length-2][1] === last[1]) {
result.pop();
}
continue;
}
result.push(current);
}
return result;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.