The Skyline Problem solution explained

The Skyline Problem gives you rectangular buildings as [left, right, height] on a flat ground and asks for the outline seen from far away, as a list of points where the outline's height changes. Sweep from left to right over the building edges while keeping the heights of the buildings currently under the sweep in a max-heap (or an ordered multiset); after handling each x, the tallest live height is the outline there, and you record a point whenever it differs from the last one. That is O(n log n) for n buildings, versus O(n²) for checking every edge against every building.

By Published 8 min read

What the output means

Each building is a rectangle from x = left to x = right with the given height, standing on the ground at height 0. Seen from a distance, the buildings merge into one outline. Describe it as points [x, h], sorted by x, each saying "from here to the next point, the outline is at height h". The last point always has height 0, where the last building ends. Two consecutive points must not have the same height; if the outline stays level across a building edge, no point is written there.

Cities made up for this page
BuildingsOutline
[1, 4, 3], [2, 6, 5], [7, 9, 2][1, 3], [2, 5], [6, 0], [7, 2], [9, 0]
[1, 10, 2], [3, 5, 8][1, 2], [3, 8], [5, 2], [10, 0]
[0, 3, 4], [3, 5, 4][0, 4], [5, 0] (no point at 3: the height does not change)
[0, 4, 5], [4, 8, 2][0, 5], [4, 2], [8, 0]
Cities made up for this page. Scroll sideways on a small screen.

Why it is a classic hard question

Nothing here is a trick, but several small decisions must all be right at once: which x values matter, how to know which buildings cover a point, how to remove a building from a heap, and what to do when several edges share one x. Interviewers use it to see whether you can find the sweep-line idea, pick a data structure that supports "largest live value" with removals, and then reason carefully about ordering. Explaining a brute force first, then improving it, is the expected path.

Brute force over the edges

The outline is flat between consecutive building edges, so only edge x values matter. For each one, find the tallest building that covers it, meaning left <= x < right (a building no longer counts at its right edge). Write a point whenever that height differs from the previous point. With 2n edges and n buildings to scan per edge, this is O(n²), and it is short enough to double as a test oracle.

def skyline_brute(buildings):
    xs = sorted({x for left, right, _ in buildings for x in (left, right)})
    result = []
    for x in xs:
        height = max([h for left, right, h in buildings if left <= x < right], default=0)
        if not result or result[-1][1] != height:
            result.append([x, height])
    return result
Check every building at every edge. O(n²) time.

Sweep with a max-heap

Instead of rescanning every building at each edge, keep the buildings that are currently live. Sort all edges by x. At a left edge, the building becomes live; at a right edge, it stops being live. The answer at x is the largest live height, which a max-heap gives in O(1) after O(log n) updates.

Python's heap cannot remove an arbitrary item cheaply, so the usual move is lazy removal: store each building in the heap with its right edge, and before reading the top, pop any entries whose right edge is at or before the current x. Buildings that ended but are not on top stay in the heap; they are harmless until they rise to the top, and then they are popped. A ground entry with an infinite right edge keeps the heap from ever being empty.

import heapq

def get_skyline(buildings):
    events = []
    for left, right, height in buildings:
        events.append((left, -height, right))   # a start; taller starts sort first at the same x
        events.append((right, 0, 0))            # an end: only a cue to clean up the heap
    events.sort()
    result = []
    live = [(0, float('inf'))]                  # (-height, right); the ground never ends
    for x, neg_height, right in events:
        if neg_height:
            heapq.heappush(live, (neg_height, right))
        while live[0][1] <= x:                  # lazy removal of buildings already over
            heapq.heappop(live)
        height = -live[0][0]
        if not result or result[-1][1] != height:
            result.append([x, height])
    return result
Event sweep with a lazily cleaned max-heap (negated heights). O(n log n).

Walking the first city: at x = 1 the height-3 building goes in and the outline becomes 3. At x = 2 the height-5 building goes in, giving 5. At x = 4 the height-3 building ends, but it is not on top, so nothing is popped and the outline stays 5. At x = 6 the 5 is popped, then the stale 3 under it, leaving the ground: 0. At 7 the outline rises to 2 and at 9 falls back to 0.

Ordering events at the same x

When several edges share one x, a careless order produces extra points, such as a drop to 0 followed by a rise at the same x. Two rules keep it clean. Process starts before ends at the same x, so a building that begins exactly where another ends is already live when the old one is removed. Among starts, take the tallest first, so the outline jumps straight to its final height. In the Python version both rules come from sorting tuples (x, -height, right) with end events encoded as (x, 0, 0). Because the heap is cleaned of everything ending at or before x on the first event at that x, the height read there is already final, and later events at the same x cannot add a second point.

C++ with a multiset

In C++, a std::multiset of live heights supports insert, erase-one and read-the-largest in O(log n), so lazy removal is not needed. Encoding a start as (x, -height) and an end as (x, height) makes a plain sort apply both ordering rules: negative values come first, so starts precede ends and taller starts come first; ends at the same x come off shortest first, which avoids a stepwise drop.

#include <algorithm>
#include <set>
#include <utility>
#include <vector>
using namespace std;

vector<vector<int>> getSkyline(const vector<vector<int>>& buildings) {
    vector<pair<int, int>> events;              // (x, -height) starts, (x, height) ends
    for (const auto& b : buildings) {
        events.push_back({b[0], -b[2]});
        events.push_back({b[1], b[2]});
    }
    sort(events.begin(), events.end());         // starts before ends at one x, taller starts first
    multiset<int> heights = {0};
    vector<vector<int>> result;
    int current = 0;
    for (const auto& [x, h] : events) {
        if (h < 0) heights.insert(-h);
        else heights.erase(heights.find(h));    // erase one copy, not every equal height
        int top = *heights.rbegin();
        if (top != current) {
            result.push_back({x, top});
            current = top;
        }
    }
    return result;
}
C++17 sweep with std::multiset. O(n log n) time, O(n) space.

The comment on erase matters. Calling heights.erase(h) with a value removes every copy of that height, which silently ends other buildings of the same height. Erasing through an iterator from find removes exactly one.

Complexity

n buildings
ApproachTimeExtra space
Every edge against every buildingO(n²)O(n)
Sweep with a lazy max-heapO(n log n)O(n)
Sweep with a multisetO(n log n)O(n)
Divide and conquer: merge two halves' outlinesO(n log n)O(n)
n buildings. Scroll sideways on a small screen.

The divide and conquer version splits the buildings in half, solves each half, and merges the two outlines like merging sorted lists, taking the larger of the two current heights at each x. It is elegant and worth mentioning, though the sweep is usually quicker to write correctly under time pressure.

Cases to test

  • One building: two points.
  • A building inside a taller, wider one, which adds no points.
  • Two buildings of the same height touching end to start, which must merge into one flat run.
  • Two buildings with the same left edge and different heights.
  • Two overlapping buildings of the same height that end at different x, the case that breaks erase-by-value.

Frequent bugs

  • Treating a building as live at its right edge (left <= x <= right), which delays every drop.
  • Writing a point at every event instead of only when the height changes.
  • Processing ends before starts at the same x, which creates a dip to a lower height and back.
  • Removing every copy of a height from the multiset.
  • Forgetting the ground, so the heap or set is empty and reading the top fails.

Explaining it in an interview

Fictional example

From edges to a heap
Candidate
The outline can only change at a building edge, so I'll sweep the edges left to right. At each x the height is the tallest building that has started and not ended.
Candidate
That's a running maximum with removals. I'll use a max-heap that stores each height with its right edge, and before reading the top I pop anything that already ended.
Interviewer
What if two edges share an x?
Candidate
Starts go before ends, and taller starts first, so the height I read at that x is final and I only write a point when it changes. Sorting plus heap work is n log n.

Practice next

Minimum Number of Arrows to Burst Balloons is a gentler sort-then-sweep over ranges, and the intervals pattern guide collects the rest. For another heap that tracks a moving boundary, try Find Median from Data Stream. Minimum Falling Path Sum is a change of pace into DP.

Rehearsing with Natively

With this many small decisions, the explanation matters as much as the code. In practice on Mac or Windows, Natively can read the skyline problem from a screenshot and show an approach and code in its overlay, which you can compare with your event ordering and removal strategy. Say your reasoning aloud during a mock session and the transcript it keeps will show whether the same-x rules came through clearly. Read more about the AI interview assistant.

Questions people ask

How do you solve the Skyline Problem?

Sort all building edges by x and sweep. Keep the heights of live buildings in a max-heap or multiset; after each x, the tallest live height is the outline, and you record [x, height] whenever it changes.

What is the time complexity of the Skyline Problem?

O(n log n) for n buildings with a heap or multiset sweep. Checking every building at every edge is O(n²).

How do you remove buildings from a heap in the Skyline Problem?

Use lazy removal: store each height with its right edge, and before reading the top, pop entries whose right edge is at or before the current x. In C++, a multiset can erase one copy directly.

How do you handle edges at the same x in the Skyline Problem?

Process starts before ends and taller starts first, so the outline jumps straight to its final height and no extra points appear.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP