Problem Description
Given the locations and heights of all the buildings in a city, return the skyline formed by these buildings collectively. The skyline should be represented as a list of key points sorted by their x-coordinate. Each key point is the left endpoint of some horizontal segment in the skyline, except the last point which always has a y-coordinate of 0 to mark the skyline's termination.
Key Insights
- The skyline can be determined using a line sweep algorithm combined with a max-heap (priority queue) to keep track of active building heights.
- By processing "events" (start and end of buildings), we can determine when to add or remove heights from the skyline.
- We must ensure that consecutive points with the same height are merged to avoid horizontal lines in the output.
Space and Time Complexity
Time Complexity: O(N log N) - where N is the number of buildings, due to sorting and heap operations. Space Complexity: O(N) - for storing the heights in the heap and the output list.
Solution
To solve this problem, we will use the line sweep algorithm. We will create a list of events for each building: one for the start (left edge) and one for the end (right edge). We will sort these events primarily by the x-coordinate, and in case of ties, we will prioritize the start of a building over its end. We will utilize a max-heap to keep track of the current active building heights. As we process each event, we will compare the current maximum height with the height from the heap and record key points whenever there is a change in height.