We are going to solve the classic "Skyline Problem". Given a list of buildings, each represented as [left, right, height], we want to compute the skyline formed by these buildings.
We'll choose the sweep-line algorithm because it is efficient (O(n log n)) and can be implemented with a heap.
-
Create a list of events: for each building [left, right, height], we create two events:
- (left, -height) // negative to indicate the start of a building, and we want to process starts before ends at same x?
- (right, height) // positive for end
But note: at the same x-coordinate, we should process the higher start before lower start? and ends before starts? Actually, we need to be careful.
Standard approach:
- For start: we want to add the building to the heap, so we use negative height to ensure that when we sort by x, and then by height (for same x), we process the higher start first (so that the max height changes to the new building's height).
- For end: we remove the building from the heap. But note: we cannot remove an arbitrary element from a heap easily (unless we use a heap with lazy removal). Alternatively, we can use a max-heap and mark the building as removed when we see the end event.
However, we can also do:
- Sort the events by x-coordinate.
- For same x:
- If both are starts, we want the higher building to be processed first (so that the max height becomes that higher one).
- If both are ends, we want the lower building to be processed first? Actually, when we remove, we want to remove the building that ends, but note that multiple buildings might end at the same x. We want to remove all of them, but the order of removal doesn't matter as long as we update the max height after each removal? However, we are going to use a heap and we are going to do lazy removal.
-
We'll use a max-heap (in Python, we use min-heap with negative values) to keep track of the current heights. But note: we need to remove a specific building when we see its end event. Since we cannot remove from a heap arbitrarily, we use a lazy removal technique:
- We'll maintain a heap of current heights (negative for max-heap) and a counter (or a set) of buildings that have ended but are still in the heap.
However, note that the same building might appear multiple times in the heap? We only add each building once (at its start). But we might have multiple events that require removal of the same building? No, each building has exactly one start and one end.
But we might have multiple buildings with the same height? Yes, but they are distinct. So we can use a dictionary or a counter to track how many times a height has been removed? Actually, we can do:
We'll store in the heap the height (negative) and also the building's right coordinate? Not necessary for removal.
Instead, we can do:
Let's maintain:
heap: a max-heap (using negative) of current active building heights.
removed: a dictionary (or Counter) that counts how many times a particular height has been removed (but note: multiple buildings can have same height).
But wait: when we see an end event (right, height), we want to remove that specific building. However, in the heap we only have the height. If there are two buildings with the same height, and one ends, we cannot distinguish which one to remove.
So we need to store more information in the heap. Alternatively, we can store (height, right) in the heap? Then when we see an end event, we know that the building with that right and that height is ending? But note: two buildings could have same height and same right? Then we cannot distinguish.
Alternatively, we can assign an id to each building? But that complicates.
Another common approach: we store in the heap only the heights, but when we see an end event, we mark that one instance of that height is removed. However, if two buildings have the same height, we don't know which one to remove. But note: if two buildings have the same height, and one ends, then the max height might change only if that building was the one contributing to the max? Actually, if there are two buildings of height 10, and one ends, the max remains 10. So we can use a counter for each height.
But wait: what if the building that ends is the one that was the current max? Then we need to remove it and then the next max might be the same height (from another building) or lower.
So we can do:
We'll have:
heap: a max-heap (negative) of heights that are currently active.
count: a dictionary that maps height (positive) to the number of active buildings with that height.
However, note: we are storing negative in the heap, but the count dictionary uses positive? We can use the absolute value.
Steps:
For each event (x, h):
if h < 0 (start event):
height = -h
push height into heap (as negative? Actually, we want max-heap, so we push -height? But then we have to remember to negate when popping? Let's be consistent:
Let's define:
We'll use a min-heap for negative heights, so that the smallest negative is the highest building? Actually, to get max, we can push negative and then pop the smallest (which is the most negative) and then negate to get the max.
Alternatively, we can use a max-heap by pushing negative and then when we want the max, we take the smallest element (which is the most negative) and then negate.
But in Python, heapq is a min-heap. So we can store negative of the height to simulate max-heap.
So:
For start event (x, -height):
we push -height into the heap? Actually, the event gives us (x, -height) for start. So we can push the negative of that? Wait:
Let me define:
event = (x, h) where:
if h < 0: it's a start, and the building height is -h.
if h > 0: it's an end, and the building height is h.
Then:
Start:
building_height = -h
we push -building_height? That would be h? But h is negative. Wait:
Example: building [2,9,10] -> start event: (2, -10), end event: (9,10).
For start: we want to add 10 to our active set. How do we represent in the heap? We want a max-heap, so we push -10? Then the smallest in the heap (most negative) is -10, which corresponds to 10.
But note: the event gives us (2, -10). So we have h=-10. Then building_height = -h = 10. Then we push -building_height = -10.
Alternatively, we can just push h (which is -10) and then when we look at the heap, the top is the smallest (most negative) which corresponds to the largest building.
So for start, we push h (which is negative) into the heap.
For end, we have h positive (the building height). But note: we have to remove an instance of that height. However, in the heap we stored the negative of the height for that building? Wait:
We stored for a building of height 10: we pushed -10.
So when we see an end event with h=10, we want to remove one instance of -10 from the heap? But the heap has -10. So we can record that we have removed one -10? Then when we clean the heap, we remove the top if it has been marked as removed.
But note: we might have multiple buildings with the same height, so we might have multiple -10 in the heap. So we need to know how many of the -10 are still active.
Alternatively, we can store in the heap the height (as negative) and also the right coordinate? Then when we see an end event, we know the building that ends is (height, right). But then we have to remove that specific (height, right) from the heap? We cannot do that with heapq.
So the lazy removal with a counter is better.
Let's define:
heap: a list that we use as a max-heap by storing negative heights.
removed: a Counter (or dictionary) that counts how many times a particular (negative) height has been removed.
But note: the same building height might be added multiple times (from different buildings) and then removed multiple times.
So when we push, we push the negative of the building height (so for height 10, we push -10).
When we see an end event with height=10, we do:
removed[-10] += 1 # because we stored -10 for that building.
Then, when we want to get the current max height, we do:
while heap and removed[heap[0]] > 0:
removed[heap[0]] -= 1
heapq.heappop(heap)
Then, if heap is not empty, current_max = -heap[0] (because heap[0] is the smallest negative, which is the most negative, so the largest building).
If heap is empty, current_max = 0.
However, note: we might have multiple buildings with the same height, and we are storing the same negative value multiple times. Then when we remove one, we decrement the counter for that negative value and pop one instance from the heap.
But wait: what if we have two buildings of height 10? Then we push -10 twice. Then when one ends, we remove one -10, so the counter for -10 becomes 1. Then when we clean the heap, we see the top is -10, and the counter for -10 is 1, so we pop that one and set counter to 0. Then the next top might be another -10? But we only have one left? Actually, we have two -10 in the heap. We popped one, so now there is one left. But the counter for -10 is now 0? We set it to 0 after popping? Actually, we decrement the counter and then pop. So after the first removal, the counter becomes 1 (if initially 0) and then we pop and set counter to 0? Let's trace:
Initially: heap = [-10, -10], removed[-10] = 0.
End event for one building of height 10:
removed[-10] += 1 -> becomes 1.
Then when we clean:
heap[0] = -10, removed[-10] = 1 > 0 -> so we pop one -10 and set removed[-10] to 0? Actually, we do:
removed[heap[0]] -= 1 -> becomes 0.
heapq.heappop(heap) -> now heap has one -10.
Then current_max = -(-10) = 10.
So that works.
But note: we are using the heap to store the negative heights, and we are using the same negative value for multiple buildings of same height. And the counter counts how many of that negative value are to be removed.
However, what if we have two buildings with different heights? Then we have different negative values in the heap, and the counter for each.
This should work.
-
Algorithm:
events = []
for each building [l, r, h]:
events.append( (l, -h) ) # start event: note we use negative h for start to ensure that when sorted, higher starts come first at same x.
events.append( (r, h) ) # end event
sort events by:
first by x, then by h (so that for same x, negative (starts) come before positive (ends)? Actually, we want to process starts before ends at same x? Not exactly: we want to add new buildings before removing old ones? Actually, consider:
Two buildings:
A: [1,5,3]
B: [5,7,4]
At x=5, we have the end of A and the start of B. The skyline at x=5 should be 4 (the start of B). So we should process the start before the end? But wait, the point at x=5: if we process end first, then we remove A and then add B, so the max becomes 4. But if we process start first, then we add B (so current max becomes max(3,4)=4) and then remove A (which was 3) so max remains 4. So both orders work? But what if:
A: [1,5,5]
B: [5,7,3]
At x=5, we want the skyline to drop from 5 to 3? Actually, the building A ends at 5, and B starts at 5. The skyline at x=5 should be 3? But note: the building B starts at 5, so at x=5, both A and B are present? Typically, we consider that the building A covers [left, right) or [left, right]? The problem usually defines the building as covering [left, right) (left inclusive, right exclusive). So at x=5, building A is no longer there (because right=5, and we consider up to but not including 5). So the point at x=5 is the start of B? So we want to have a point at (5,3). So we should process the end of A first? Then the current max becomes 0 (if no other building) and then we add B (3). So we get a point at (5,3). But if we process start first, then at x=5 we add B (3) and then remove A (5) -> current max becomes 3. So we get the same.
However, the key point is that we want to avoid having two consecutive points with the same height? The merge step in divide and conquer does that by checking the last point.
In the sweep-line, we are going to record a point only when the current max height changes.
So the order at same x might not matter for the current max? But we have to be cautious.
Standard solution: sort by x, and for same x, sort by h (so that negative (starts) come before positive (ends)). But note: if we have two starts at same x, we want the higher one to come first? Because if we add a lower one first, then the max becomes the higher one when we add the higher one, so we get the same result. But if we add the higher one first, then when we add the lower one, the max doesn't change. So it's better to add the higher one first? Actually, we want to set the current max to the highest among the starts at that x. So if we process the higher one first, then the current max becomes that higher one, and then when we process the lower one, the max remains the same. So we avoid an extra point? But then when we remove, we might remove the higher one and then the lower one becomes the max? But that's at a different x.
Actually, at the same x, if we have multiple starts and ends, we want to process all starts first? Because if we process an end first, we might drop the current max and then a start might bring it back up, but we would record a drop and then a rise at the same x? We don't want two points at the same x.
The typical approach is:
Sort events by x, and for same x:
- If one is start and one is end: we want to process the start before the end? Or the other way? Let's see:
Consider:
Event1: (x, start, h1)
Event2: (x, end, h2)
We want at x to have the effect of both. But note: if we process end first, then we remove h2 and then add h1. The current max after processing both will be max( (current max without h2) , h1). But if we process start first, then we add h1 and then remove h2. The current max after both will be max( (current max with h1) without h2). These might be different? Example:
Current max before x: 10.
h1 = 5, h2 = 10.
If we process end first: remove 10 -> current max becomes 0? Then add 5 -> current max becomes 5.
If we process start first: add 5 -> current max becomes 10 (because 10 was still there? Wait, we haven't removed 10 yet). Then remove 10 -> current max becomes 5.
So the result after processing both is the same? Not necessarily: if there is another building of height 10 that doesn't end at x, then:
Current max before x: 10 (from building A and building B both of height 10).
Event1: end of building A (h2=10)
Event2: start of building C (h1=5)
If we process end first: remove A -> current max remains 10 (from B) -> then add C (5) -> max remains 10.
If we process start first: add C (5) -> max remains 10 -> remove A -> max remains 10.
So same.
But what if:
Current max before x: 10 (from building A of height 10).
Event1: end of A (h2=10)
Event2: start of C (h1=15)
If we process end first: remove A -> current max becomes 0 -> then add C (15) -> max becomes 15.
If we process start first: add C (15) -> max becomes 15 -> remove A -> max remains 15.
So same.
So it seems the order of start and end at same x doesn't matter? But wait, what about having two starts at same x? We want to set the current max to the highest among them. If we process a lower start first, then the current max might become that lower one (if the previous max was lower) and then when we process the higher one, it becomes the higher. But then we would record a change from previous max to the lower and then to the higher? But we only record when the current max after processing all events at that x changes? Actually, we are going to process events at the same x one by one, and after each event we check the current max? Or we process all events at the same x and then check the current max?
The standard approach is to process all events at the same x, and then after processing all, we check the current max. But then the order of events at same x doesn't matter? Because we are going to update the current max after each event? Actually, we are going to update the current max after each event and record a point if it changes? But then we would record multiple points at the same x? We don't want that.
So we should process all events at the same x and then take the max after all of them. But then we have to be careful: if we have multiple starts and ends at same x, we want to add all starts and remove all ends, and then take the max of the remaining active set.
Therefore, we should:
Group events by x.
For each x, process all events at that x:
For each event:
if start: push the negative height.
if end: increment the removed counter for that negative height? But wait: for end event, we have positive height. We stored negative in the heap. So we need to mark that we are removing a building of that height. But we stored the negative of the height. So for an end event with height h, we mark removed[-h] += 1.
Then, after processing all events at that x, we clean the heap (lazy removal) and get the current max.
So we don't necessarily need to sort the events within the same x by start/end? We just need to process all of them and then clean.
But note: if we have multiple events at the same x, we might have the same building appearing twice? No, each building has one start and one end, and they are at different x.
So we can do:
events sorted by x.
Then we iterate through events, and for each x, we process all events at that x (by checking while next event has same x) and then after that, we clean the heap and get the current max.
However, we must be cautious: if we have multiple events at same x, we want to process all of them before checking the current max.
So the algorithm:
events = sorted(events, key=lambda x: (x[0], x[1]))
But note: we want to process all events at same x together. So we can group by x.
Alternatively, we can iterate with an index and process all with same x.
Steps:
heap = [] # min-heap of negative heights.
removed = defaultdict(int)
result = []
prev_max = 0
i = 0
while i < len(events):
x = events[i][0]
# process all events at x
while i < len(events) and events[i][0] == x:
h = events[i][1]
if h < 0:
heapq.heappush(heap, h) # h is negative, so we push the negative of the building height.
else:
# h is positive, so the building height is h, and we stored -h in the heap.
removed[-h] += 1
i += 1
# clean the heap: remove tops that have been marked as removed.
while heap and removed[heap[0]] > 0:
removed[heap[0]] -= 1
heapq.heappop(heap)
curr_max = -heap[0] if heap else 0
if curr_max != prev_max:
result.append( (x, curr_max) )
prev_max = curr_max
return result
But wait: what about the case when we have multiple events at same x and the current max changes multiple times during processing? We are only recording after processing all events at that x. That is correct because we want the skyline to reflect the state after all changes at that x.
However, note: the events at the same x might be both starts and ends. We process all, then we clean the heap, and then we get the current max. This is the correct approach.
But there is a catch: what if we have a start and an end at the same x, and the start is higher than the end? Then after processing both, the current max might be the same as before? Example:
Previous max: 10.
At x:
start: 5
end: 10
After processing: we remove 10 and add 5. The current max becomes 5? But wait, what if there was another building of 10 that doesn't end? Then after removing one 10, the max remains 10. But we don't know that because we only removed one instance.
Our algorithm:
We push the start (5) -> heap now has -5 and -10 (assuming there was a -10 from before).
Then we mark for removal one -10 (because end of 10).
Then we clean: the top of heap is -10 (the most negative). We check removed[-10] -> it's 1, so we pop that -10 and set removed[-10] to 0.
Then the next top is -5. So current max = 5.
That's correct because the building of 10 ended, so the max becomes 5.
But if there were two buildings of 10, and one ends, then:
heap: [-10, -10, -5]
removed[-10] = 1
After cleaning: we pop one -10 (because top is -10 and removed[-10] is 1). Then heap becomes [-10, -5] (but note: the heap property might not be maintained? Actually, after popping, we need to heapify? But we are using heapq, and we pop the top, then the next top is the next smallest? Actually, after popping, the heap is still a heap? We use heapq.heappop which maintains the heap.
Then current max = -(-10) = 10.
So that's correct.
-
However, note: the events are sorted by x and then by h? But we are grouping by x and then processing in the order of the events? The order within the same x might matter for the intermediate state, but we are only interested in the state after processing all. So we don't need to sort by h within the same x? Actually, we do because we are processing one by one and updating the heap and the removed counter. But if we have two starts at the same x, we push both, and then when we clean, we remove the ones that are marked for removal? But at the same x, we might have both starts and ends. The order of processing within the same x does not affect the final state (because we are going to clean at the end) but it might affect the intermediate state? But we only record after cleaning. So it's safe.
However, consider:
At same x:
start: 5
end: 10
If we process the end first:
removed[-10] += 1 -> now we have a -10 in the heap that is to be removed.
then we push -5.
Then we clean: we see the top is -10 (if there was a -10 in the heap) and remove it. Then the top becomes -5? But what if the heap had two -10? Then after removing one, the top is still -10? Then current max is 10? But we removed one 10 and added 5, so if there was another 10, then max remains 10. That's correct.
If we process the start first:
push -5.
then removed[-10] += 1.
Then clean: if the top is -10 (from the existing building) and we have removed[-10]=1, then we pop that -10. Then the top becomes -5? But wait, we just pushed -5, so the heap has [-10, -5] and then we pop the -10 (if it was the top). Then the top becomes -5. So current max becomes 5.
But in the first order (end then start) we might have popped the -10 that was already in the heap, and then the top becomes -5? Actually, in the first order, after pushing -5, the heap is [-10, -5, ...] and then we clean: we see top is -10 and removed[-10] is 1, so we pop that -10. Then the heap becomes [-5, ...] and the top is -5. So same.
So the order doesn't matter.
But what if we have two ends at the same x? Then we mark two removals. Then when cleaning, we remove two tops if they are the ones marked? But note: the two ends might be for two different heights. Then we mark removed for each. Then when cleaning, we remove the top if it is marked, and then check the next top? But what if the top is not marked? Then we stop. That's correct because we only remove the buildings that ended.
Example:
Heap: [-10, -8, -5] (so max is 10)
At same x, we have two ends:
end of 10 -> removed[-10] +=1
end of 5 -> removed[-5] +=1
Then we clean:
top is -10, removed[-10] is 1 -> pop and set removed[-10] to 0.
now heap: [-8, -5] -> top is -8, removed[-8] is 0 -> stop.
current max = 8.
That's correct.
So we don't need to sort by h within the same x? Actually, we do because the events are given and we are processing in the order of the events. But if we group by x and then process in any order, it should be the same? But note: the events list might have the same x but with different h. We are grouping by x and then processing in the order they appear in the sorted events? But we sorted by (x, h). Does the h matter for the order? We want to process all events at the same x, but the order of processing within the same x doesn't affect the final state because we are only recording after all events. However, the intermediate state (during processing) might affect which elements are popped when we clean? But we clean after all events. So the order of processing within the same x doesn't matter for the final state.
-
But wait: what about the case when we have a start and an end at the same x, and the start is for a building that is higher than the building that ends? We already saw it doesn't matter.
-
However, there is a known issue: if we have multiple events at the same x, and we are using lazy removal, we might have a situation where the top of the heap has been removed but not yet popped? But we clean at the end of processing all events at that x. So we are safe.
-
But note: we are cleaning only once after processing all events at that x. What if during the processing of events at that x, we have a removal that makes the top of the heap invalid? We don't clean until the end. That's okay because we are going to clean at the end.
Example:
Heap: [-10, -8, -5]
At x, we have:
end of 10 -> removed[-10] +=1
then we push a start of 7 -> push -7.
Now the heap is [-10, -8, -5, -7] (but note: the heap property might be broken? Actually, when we push -7, the heap will adjust. The smallest (most negative) is still -10.
Then we clean: we see top is -10 and removed[-10] is 1, so we pop -10. Then the heap becomes [-8, -7, -5]? Actually, after popping, the heap is adjusted: the new top is -8.
Then current max = 8.
That's correct because we removed 10 and added 7, so the max becomes 8.
So it's correct.
-
One more issue: what if we have a start event for a building that is lower than the current max? Then pushing it doesn't change the current max. But we don't record until after processing all events at that x. So we won't record a point for that start because the current max doesn't change? But wait, what if the current max was from a building that ends at the same x? Then we remove the current max and the new max becomes the new start? But we are processing all events at that x, so the removal and the start are both processed, and then we take the max of the remaining.
Example:
Current max: 10.
At x:
end of 10
start of 5
After processing: we remove 10 and add 5. The heap becomes [ -5 ] (if there were no other buildings). Then current max becomes 5. So we record (x,5). That's correct.
But if we had:
Current max: 10.
At x:
start of 15
end of 10
After processing: we remove 10 and add 15. The heap becomes [-15] (if there were no other). Then current max becomes 15. So we record (x,15).
So it's correct.
-
Implementation:
We'll do:
events = []
for building in buildings:
left, right, height = building
events.append( (left, -height) )
events.append( (right, height) )
Sort events by x (only by x).
Then:
import heapq
heap = [] # min-heap of negative heights.
removed = defaultdict(int)
result = []
prev_max = 0
i = 0
n = len(events)
while i < n:
# Process all events at current x
cur_x = events[i][0]
while i < n and events[i][0] == cur_x:
h = events[i][1]
if h < 0:
heapq.heappush(heap, h)
else:
removed[-h] += 1
i += 1
# Clean up the heap: remove tops that are marked as removed.
while heap and removed[heap[0]] > 0:
removed[heap[0]] -= 1
heapq.heappop(heap)
cur_max = -heap[0] if heap else 0
if cur_max != prev_max:
result.append( (cur_x, cur_max) )
prev_max = cur_max
return result
-
But wait: what about the ground? We want the last point to be at the end of the last building with height 0? Actually, we record a point when the max height changes. The last building ends, and then the max becomes 0, so we record that point.
Example: one building [0,2,3]:
events: (0,-3), (2,3)
at x=0: push -3, heap becomes [-3], current max=3 -> record (0,3)
at x=2: remove 3, heap becomes empty, current max=0 -> record (2,0)
So we get [(0,3), (2,0)].
-
However, note: the problem might require the skyline to be a list of points that define the outline. The above algorithm produces the correct points.
-
But there is a known issue: if we have two adjacent buildings with the same height, we don't want to record a drop and then rise? Actually, we only record when the current max changes. So if two buildings have the same height and are adjacent, then at the boundary, we might have:
Building A: [0,2,3]
Building B: [2,4,3]
Events:
(0,-3), (2,3) for A
(2,-3), (4,3) for B
At x=0: push -3 -> max=3 -> record (0,3)
At x=2:
first: (2,3) from A -> removed[-3] +=1 -> now removed[-3]=1.
then: (2,-3) from B -> push -3 -> heap becomes [-3, -3]? Actually, we already have one -3 from A? But we removed A? Wait, we have:
Before processing x=2: heap = [-3] (from A).
Then we process (2,3): removed[-3] becomes 1.
Then we process (2,-3): push -3 -> heap becomes [-3, -3] (two -3's).
Then we clean:
top is -3, removed[-3] is 1 -> pop one -3, set removed[-3] to 0.
now heap has one -3, top is -3, removed[-3] is 0 -> stop.
current max = 3.
So at x=2, the current max remains 3, so we don't record a point.
Then at x=4: remove the second -3 -> heap becomes empty -> current max 0 -> record (4,0).
So we get [(0,3), (4,0)] which is correct because the skyline is just a flat line at 3 from 0 to 4.
-
Another case: two buildings with different heights that overlap:
A: [0,3,3]
B: [2,4,5]
Events:
(0,-3), (3,3)
(2,-5), (4,5)
Sorted by x:
(0,-3)
(2,-5)
(3,3)
(4,5)
At x=0: push -3 -> heap=[-3], max=3 -> record (0,3)
At x=2: push -5 -> heap=[-5,-3] (min-heap: -5 is top) -> max=5 -> record (2,5)
At x=3: remove 3 -> removed[-3] +=1 -> then clean: top is -5, removed[-5]=0 -> so we don't pop. current max remains 5 -> no record.
At x=4: remove 5 -> removed[-5] +=1 -> then clean: top is -5, removed[-5]=1 -> pop, then heap becomes empty? Actually, after popping, we check again: heap is empty? Then current max=0 -> record (4,0).
So we get [(0,3), (2,5), (4,0)].
But wait: from x=2 to x=3, the max is 5. Then at x=3, building A ends, but building B is still there until 4. So the max remains 5 until x=4. So we don't record at x=3. That's correct.
-
However, note: the above algorithm does not record the point at x=3 when building A ends because the max doesn't change. That's correct.
-
But what about the point at x=3? The building A ends at 3, but the skyline doesn't drop at 3 because building B is taller and still present. So no point at 3.
-
So the algorithm seems correct.
-
Complexity:
- Sorting: O(n log n) for 2n events.
- Each event is pushed/popped at most once: O(n log n) for heap operations.
- The lazy removal might cause us to pop more than n times? But each pop corresponds to a building that was pushed, so at most 2n pops? Actually, we push n buildings, and we pop at most n times (each building is removed once). So total heap operations O(n log n).
So overall O(n log n).
-
Let's code accordingly.
-
Edge cases:
- No buildings: return [].
- Buildings with same left and right? But typically left<right. We assume valid input.
-
However, note: the problem says "list of integers" but each building is represented by three integers? Actually, the input is a list of buildings, each building is [left, right, height].
-
Let's code accordingly.
-
One more thing: the problem might require the skyline to be in a specific format. Usually, the skyline is a list of [x, height] points. And the last point should have height 0.
-
We are returning a list of tuples (x, height). We can return as list of lists if required.
-
Let's implement.
-
But wait: what about the case when we have multiple events at the same x and the current max changes multiple times during the processing? We are only recording after processing all events at that x. That is correct because we want the skyline to reflect the state after all changes at that x.
However, consider:
Building A: [1,5,10]
Building B: [1,5,15]
Events at x=1: (1,-10), (1,-15)
Events at x=5: (5,10), (5,15)
At x=1: we push -10 and then -15. Then we clean? No removals. Then current max = 15. So we record (1,15).
At x=5: we mark removal for 10 and 15. Then clean:
heap initially: [-15, -10] (because we pushed -10 then -15? Actually, the heap property: after pushing -10, then -15, the heap becomes [-15, -10] because -15 is smaller.
Then we mark removed[-10] +=1 and removed[-15] +=1.
Then we clean:
top is -15, removed[-15] is 1 -> pop and set removed[-15]=0.
then top is -10, removed[-10] is 1 -> pop and set removed[-10]=0.
heap empty -> current max 0.
So we record (5,0).
Correct.
-
However, there is a known bug in the lazy removal approach: if we have multiple buildings with the same height, and we remove one, we mark the negative of that height for removal. But when we clean, we remove the top if it is marked. But what if the top is not the one we marked? Example:
We have two buildings of height 10: building A and building B.
We push -10 for A, then push -10 for B. The heap is [-10, -10] (but note: the heap property is maintained? Actually, both are -10, so the heap is just two -10's, and the top is -10.
Now, we end building A: we do removed[-10] +=1 -> becomes 1.
Then we clean: top is -10, removed[-10] is 1 -> so we pop one -10 and set removed[-10] to 0.
Then the heap has one -10, and removed[-10] is 0, so we stop.
Then current max = 10.
Now we end building B: removed[-10] +=1 -> becomes 1.
Then clean: top is -10, removed[-10] is 1 -> pop and set to 0.
Then heap empty.
So it works.
But what if we had:
Heap: [-10, -8] (two buildings: 10 and 8)
We end the building of 10: removed[-10]=1.
Then we clean: top is -10, removed[-10]=1 -> pop -10. Then heap becomes [-8]. Then current max=8.
Correct.
-
But consider:
Heap: [-10, -8, -5]
We end the building of 8: removed[-8]=1.
Then we clean: top is -10, removed[-10]=0 -> stop. So we don't pop anything? But we have a removed building of 8 that is not at the top. That's okay because we only remove from the top when we clean. But then the heap still has -8? Yes, but we have marked that one -8 is to be removed. Then when we later remove the -10 (by an end event of 10) and then clean, we might pop the -8? But note: we are only cleaning at the end of each x. So at the x where we ended 8, we didn't clean because the top was -10 and not removed. Then at the next x, if we have no events, we don't clean? Actually, we only clean when we are about to check the current max. So at the next x, we process events and then clean. Then if the top becomes -8 (after popping -10) and removed[-8] is 1, then we pop it.
So it's okay.
-
However, there is a potential memory leak: the heap might contain many removed elements that are not at the top. But we remove them lazily when they become the top. This is standard.
-
Let's code accordingly.
-
One more thing: the events must be sorted by x. But what if two events have the same x? We don't care about the order because we process all at that x. So we can sort by x only.
-
But note: the standard solution often sorts by (x, h) to handle the case where we have a start and an end at the same x and the start is for a building that is taller than the one that ends? But as we saw, it doesn't matter. However, there is a subtle case:
Consider two buildings:
A: [1,3,3]
B: [3,5,5]
Events:
(1,-3), (3,3) for A.
(3,-5), (5,5) for B.
At x=3, we have:
end of A (3) and start of B (5).
If we process the end of A first:
removed[-3] +=1.
then push -5.
Then clean:
heap initially: [-3] (from A). After push: [-5, -3]? Actually, when we push -5, the heap becomes [-5, -3] (because -5 < -3). Then we clean: top is -5, removed[-5]=0 -> stop. So current max=5.
If we process the start of B first:
push -5 -> heap becomes [-5, -3] (if we had -3 from A).
then removed[-3] +=1.
Then clean: top is -5, removed[-5]=0 -> stop. current max=5.
So same.
But what if the start of B was lower than the end of A?
A: [1,3,5]
B: [3,5,3]
Events at x=3:
(3,5) and (3,-3)
Process end of A first:
removed[-5] +=1.
then push -3.
heap initially: [-5] (from A). After push: [-5, -3]? Actually, when we push -3, the heap becomes [-5, -3] (because -5 < -3). Then clean: top is -5, removed[-5]=1 -> pop -5. Then heap becomes [-3]. current max=3.
Process start of B first:
push -3 -> heap becomes [-5, -3] (same).
then removed[-5] +=1.
Then clean: top is -5, removed[-5]=1 -> pop -5. Then heap becomes [-3]. current max=3.
Same.
So it's safe.
-
However, note: the heap after pushing and before cleaning might have the removed element at the top? But we clean after all events at that x. So it's okay.
-
Let's code accordingly.
-
But wait: what if we have multiple ends at the same x and the top of the heap is not one of the ended buildings? Then we don't pop? That's correct because the top is still active.
Example:
Heap: [-10, -8, -5]
At x, we have two ends: for 8 and 5.
We mark removed[-8] +=1 and removed[-5] +=1.
Then we clean: top is -10, removed[-10]=0 -> stop. So the heap remains with -10, -8, -5? But we have marked -8 and -5 for removal. They are still in the heap. That's okay because they are not at the top. When the top (which is -10) is eventually removed (by an end event for 10) then we will clean and then the next top might be -8, and then we see removed[-8] is 1, so we pop it, and then the next top might be -5 and we pop it.
So the lazy removal works.
-
Implementation:
We'll use:
import heapq
from collections import defaultdict
Steps:
def get_skyline(buildings):
if not buildings:
return []
events = []
for b in buildings:
l, r, h = b
events.append((l, -h)) # start
events.append((r, h)) # end
events.sort(key=lambda x: x[0]) # sort by x only
heap = [] # min-heap for negative heights.
removed = defaultdict(int)
result = []
prev_max = 0
i = 0
n = len(events)
while i < n:
cur_x = events[i][0]
# Process all events at cur_x
while i < n and events[i][0] == cur_x:
h = events[i][1]
if h < 0:
heapq.heappush(heap, h)
else:
removed[-h] += 1
i += 1
# Remove invalidated tops
while heap and removed[heap[0]] > 0:
removed[heap[0]] -= 1
heapq.heappop(heap)
cur_max = -heap[0] if heap else 0
if cur_max != prev_max:
result.append([cur_x, cur_max])
prev_max = cur_max
return result
-
Let's test with the example from LeetCode:
Input: [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
Expected: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
But note: the expected output might vary? Actually, the problem usually expects:
[[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
Let's simulate:
Events:
(2,-10), (9,10)
(3,-15), (7,15)
(5,-12), (12,12)
(15,-10), (20,10)
(19,-8), (24,8)
Sorted by x:
(2,-10)
(3,-15)
(5,-12)
(7,15)
(9,10)
(12,12)
(15,-10)
(19,-8)
(20,10)
(24,8)
Process:
i=0, cur_x=2: push -10 -> heap=[-10], clean (none), cur_max=10, prev_max=0 -> record (2,10), prev_max=10.
i=1, cur_x=3: push -15 -> heap=[-15,-10] (min-heap: -15 is top), clean, cur_max=15, record (3,15), prev_max=15.
i=2, cur_x=5: push -12 -> heap=[-15,-10,-12]? Actually, after push, the heap becomes [-15, -10, -12] (but note: the heap property: the smallest is at index0, then the two children are larger. So it's okay). Then clean: top is -15, not removed. cur_max=15, same as prev_max -> no record.
i=3, cur_x=7: end of 15 -> removed[-15] +=1 -> now removed[-15]=1. Then clean: top is -15, removed[-15]=1 -> pop -15, set removed[-15]=0. Then heap becomes [-12,-10]? Actually, after popping, we need to heapify. The heap becomes [-12, -10] (because -12 < -10). Then cur_max = 12. Record (7,12), prev_max=12.
i=4, cur_x=9: end of 10 -> removed[-10] +=1 -> now removed[-10]=1. Then clean: top is -12, removed[-12]=0 -> stop. cur_max=12, same -> no record.
i=5, cur_x=12: end of 12 -> removed[-12] +=1 -> now removed[-12]=1. Then clean: top is -12, removed[-12]=1 -> pop -12, set removed[-12]=0. Then heap becomes [-10]? But wait, we have removed[-10]=1. Then we clean again? The loop continues: now top is -10, removed[-10]=1 -> pop -10, set removed[-10]=0. Then heap empty -> cur_max=0. Record (12,0), prev_max=0.
i=6, cur_x=15: push -10 -> heap=[-10], clean, cur_max=10, record (15,10), prev_max=10.
i=7, cur_x=19: push -8 -> heap=[-10,-8]? Actually, after push: [-10,-8] (because -10 < -8). Then clean: top is -10, not removed. cur_max=10, same -> no record.
i=8, cur_x=20: end of 10 -> removed[-10] +=1 -> now removed[-10]=1. Then clean: top is -10, removed[-10]=1 -> pop -10, set removed[-10]=0. Then heap becomes [-8]. cur_max=8, record (20,8), prev_max=8.
i=9, cur_x=24: end of 8 -> removed[-8] +=1 -> now removed[-8]=1. Then clean: top is -8, removed[-8]=1 -> pop -8, set removed[-8]=0. Then heap empty -> cur_max=0. Record (24,0).
So we get:
(2,10), (3,15), (7,12), (12,0), (15,10), (20,8), (24,0)
Which matches.
-
However, note: the example in LeetCode sometimes has the point (12,0) and then (15,10). So it's correct.
-
But wait: what about the point at x=5? We didn't record because the max didn't change? But from x=3 to x=7, the max is 15? Actually, at x=5, we added a building of 12, but the max remains 15. So we don't record at x=5. That's correct.
-
So the algorithm works.
-
Let's write the code accordingly.
-
One more thing: the problem might require the output to be in a specific order? We are processing in increasing x, so the output is sorted by x.
-
We return a list of [x, height].
-
Code:
import heapq
from collections import defaultdict
def get_skyline(buildings):
if not buildings:
return []
events = []
for l, r, h in buildings:
events.append((l, -h)) # start
events.append((r, h)) # end
events.sort(key=lambda x: x[0]) # sort by x
heap = [] # min-heap for negative heights
removed = defaultdict(int)
result = []
prev_max = 0
i = 0
n = len(events)
while i < n:
cur_x = events[i][0]
# process all events at cur_x
while i < n and events[i][0] == cur_x:
h = events[i][1]
if h < 0:
heapq.heappush(heap, h)
else:
removed[-h] += 1
i += 1
# remove invalidated tops
while heap and removed[heap[0]] > 0:
removed[heap[0]] -= 1
heapq.heappop(heap)
cur_max = -heap[0] if heap else 0
if cur_max != prev_max:
result.append([cur_x, cur_max])
prev_max = cur_max
return result
-
Let's test with a simple case:
buildings = [[0,2,3],[2,5,3]]
Expected: [[0,3],[5,0]]
Events:
(0,-3), (2,3)
(2,-3), (5,3)
Sorted by x:
(0,-3)
(2,3), (2,-3)
(5,3)
Process:
x=0: push -3 -> heap=[-3], cur_max=3 -> record (0,3)
x=2:
first: (2,3) -> removed[-3] +=1 -> removed[-3]=1
then: (2,-3) -> push -3 -> heap=[-3,-3]? Actually, we had one -3, now push another -> heap becomes [-3,-3] (but note: the heap property: both are -3, so the top is -3).
Then clean: top is -3, removed[-3]=1 -> pop one -3, set removed[-3]=0.
Now heap has one -3, top is -3, removed[-3]=0 -> stop.
cur_max = 3, same as prev_max -> no record.
x=5:
(5,3) -> removed[-3] +=1 -> becomes 1.
Then clean: top is -3, removed[-3]=1 -> pop, set removed[-3]=0. heap empty.
cur_max=0, record (5,0).
So we get [(0,3),(5,0)] -> correct.
-
Another test: two overlapping with same height:
buildings = [[1,3,3],[2,4,3]]
Events:
(1,-3), (3,3)
(2,-3), (4,3)
Sorted:
(1,-3)
(2,-3)
(3,3)
(4,3)
Process:
x=1: push -3 -> heap=[-3], cur_max=3 -> record (1,3)
x=2: push -3 -> heap=[-3,-3] -> cur_max=3 (same) -> no record.
x=3:
(3,3) -> removed[-3] +=1 -> becomes 1.
Then clean: top is -3, removed[-3]=1 -> pop one -3, set removed[-3]=0.
heap now has one -3, cur_max=3 -> same -> no record.
x=4:
(4,3) -> removed[-3] +=1 -> becomes 1.
Then clean: top is -3, removed[-3]=1 -> pop, set removed[-3]=0. heap empty -> cur_max=0 -> record (4,0).
So we get [(1,3),(4,0)]. That's correct because the skyline is a flat line at 3 from 1 to 4.
-
One more: two buildings, one inside the other:
A: [1,5,10]
B: [2,4,5]
Events:
(1,-10), (5,10)
(2,-5), (4,5)
Sorted:
(1,-10)
(2,-5)
(4,5)
(5,10)
Process:
x=1: push -10 -> heap=[-10], cur_max=10 -> record (1,10)
x=2: push -5 -> heap=[-10,-5] -> cur_max=10 -> no record.
x=4:
(4,5) -> removed[-5] +=1 -> removed[-5]=1.
Then clean: top is -10, removed[-10]=0 -> stop. cur_max=10 -> no record.
x=5:
(5,10) -> removed[-10] +=1 -> removed[-10]=1.
Then clean: top is -10, removed[-10]=1 -> pop -10, set removed[-10]=0.
Now heap is empty? Actually, we had two elements: -10 and -5. We popped -10. But we also had a -5 that was removed? Wait, we removed -5 at x=4? But the heap still has -5?
Let's see: at x=4, we marked removed[-5]=1. Then we cleaned: top was -10, so we didn't pop -5. So the heap still has -5? But we marked it as removed? Then at x=5, after popping -10, the heap becomes [-5]. Then we check the top: -5, and removed[-5]=1 -> so we pop -5 and set removed[-5]=0. Then heap empty.
So cur_max=0 -> record (5,0).
So we get [(1,10),(5,0)] which is correct because the inner building doesn't affect the skyline.
-
So the algorithm works.
-
However, note: the above algorithm uses lazy removal and might have a heap that grows with the number of buildings? But we are popping the removed ones when they come to the top. So the heap size is at most the number of active buildings.
-
Let's code accordingly.
-
One more edge: if the input has negative coordinates? The algorithm works because we are just comparing numbers.
-
We assume the buildings are given as [left, right, height] with left and right integers, and height positive.
-
We are done.
-
But wait: the problem says "list of integers", but each building is a list of three integers? Yes.
-
Let's write the function.
-
Note: we are using heapq and defaultdict. We must import them.
-
We'll write the function as:
import heapq
from collections import defaultdict
def skyline(buildings):
# ... as above
-
However, note: the function name in the problem statement is not specified. We'll call it skyline.
-
Let's return the result.
-
One more thing: the problem might require the output to be in a specific format? Usually, it's a list of [x, height] points.
-
We are returning that.
-
Let's test with the provided example in the code.
-
We'll write the function and then test.
-
But note: the example in the problem might have the buildings in a different order? Our algorithm doesn't depend on the order of buildings because we create events and sort.
-
We are good.
-
Code:
import heapq
from collections import defaultdict
def skyline(buildings):
if not buildings:
return []
events = []
for b in buildings:
left, right, height = b
events.append((left, -height)) # start event: negative height
events.append((right, height)) # end event: positive height
# sort by x-coordinate
events.sort(key=lambda x: x[0])
heap = [] # min-heap for negative heights
removed = defaultdict(int) # counts for removed heights (stored as negative in heap)
result = []
prev_max = 0
i = 0
n = len(events)
while i < n:
cur_x = events[i][0]
# process all events at cur_x
while i < n and events[i][0] == cur_x:
h = events[i][1]
if h < 0:
heapq.heappush(heap, h)
else:
# h is positive, so the building height is h, and we stored -h in the heap.
removed[-h] += 1
i += 1
# remove from heap top while it has been marked as removed
while heap and removed[heap[0]] > 0:
removed[heap[0]] -= 1
heapq.heappop(heap)
cur_max = -heap[0] if heap else 0
if cur_max != prev_max:
result.append([cur_x, cur_max])
prev_max = cur_max
return result
-
Let's run the example from LeetCode:
buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
print(skyline(buildings))
Expected: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
We'll run and see.
-
I'll run in my mind:
We already did and it matches.
-
But note: the example in LeetCode might have the point (12,0) and then (15,10). So it's correct.
-
However, there is a known issue: if we have a building that ends and the next event is at the same x but we have already processed that x? We process by grouping by x. So we are safe.
-
One more test:
buildings = [[0,2,3],[2,5,3]]
We did and got [[0,3],[5,0]].
-
Another test:
buildings = [[1,2,1],[1,2,2],[1,2,3]]
Events:
(1,-1), (2,1)
(1,-2), (2,2)
(1,-3), (2,3)
Sorted by x:
(1,-1), (1,-2), (1,-3), (2,1), (2,2), (2,3)
Process:
x=1: push -1, -2, -3 -> heap = [-3,-1,-2]? Actually, the heap after pushes:
push -1: [-1]
push -2: [-2,-1]
push -3: [-3,-1,-2] (because -3 is the smallest, then -1 and -2, but note: the heap property: the smallest is at index0, then the two children are larger. So the heap is stored as [-3, -1, -2]? Actually, the heap in array representation:
index0: -3
index1: -1
index2: -2
because when we push -2, it becomes the child of -1? Then when we push -3, it becomes the root and -1 and -2 become children.
Then clean: no removals. cur_max = 3. Record (1,3).
x=2:
(2,1): removed[-1] +=1 -> removed[-1]=1
(2,2): removed[-2] +=1 -> removed[-2]=1
(2,3): removed[-3] +=1 -> removed[-3]=1
Then clean:
top is -3, removed[-3]=1 -> pop -3, set removed[-3]=0.
now heap: [-2,-1]? Actually, after popping -3, the heap becomes [-2,-1] (because we take the last element and sift down). Then top is -2, removed[-2]=1 -> pop -2, set removed[-2]=0.
now heap: [-1] -> top is -1, removed[-1]=1 -> pop -1, set removed[-1]=0.
heap empty -> cur_max=0.
Record (2,0).
So we get [[1,3],[2,0]].
That's correct because all buildings are at the same place and the tallest is 3.
-
All tests pass.
-
However, note: the above algorithm might have a bug if we have a building that starts and ends at the same x? But that's not allowed because left<right.
-
We assume valid input.
-
So we are done.
-
Let's write the explanation.
We use a sweep-line algorithm combined with a max-heap (simulated with a min-heap storing negative values) and lazy removal.
Complexity: O(n log n) for sorting and heap operations, where n is the number of buildings.
This algorithm efficiently handles overlapping buildings and correctly produces the skyline by tracking the current maximum height at each critical x-coordinate.
The Skyline Problem involves computing the contour formed by a collection of rectangular buildings when viewed from a distance. Each building is represented as [left, right, height], where left and right are the x-coordinates of its vertical edges, and height is its height. The skyline is a list of critical points (x, height) where the maximum height changes, ending with (rightmost_x, 0).
This approach efficiently handles all cases, including overlapping buildings, adjacent buildings, and buildings with the same height, producing the correct skyline contour.