Taro Logo

The Skyline Problem

Hard
Asked by:
Google
Amazon
Meta
Apple
508 views
Topics:
ArraysStacksDynamic ProgrammingGreedy Algorithms

A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.

The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:

  • lefti is the x coordinate of the left edge of the ith building.
  • righti is the x coordinate of the right edge of the ith building.
  • heighti is the height of the ith building.

You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.

Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]

Example 1:

Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]
Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]
Explanation:
Figure A shows the buildings of the input.
Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.

Example 2:

Input: buildings = [[0,2,3],[2,5,3]]
Output: [[0,3],[5,0]]

Constraints:

  • 1 <= buildings.length <= 104
  • 0 <= lefti < righti <= 231 - 1
  • 1 <= heighti <= 231 - 1
  • buildings is sorted by lefti in non-decreasing order.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the structure of the input? Can we assume it is an array of arrays or tuples representing `[left, right, height]`, and are the coordinates guaranteed to be integers?
  2. What should the output format be? Should it be a list of key points represented as `[x, height]` pairs sorted by their x-coordinates?
  3. How should overlapping buildings that share the exact same height at a boundary be handled in the output? For example, if two adjacent buildings touch and have height 10, should that be merged into a single continuous flat top, or does it result in redundant points?
  4. What should be returned if the input list of buildings is empty?
  5. Can the `left` and `right` coordinates be negative, and can heights be zero?

Brute Force Solution

Approach

Imagine looking at a city skyline made of overlapping rectangular buildings and needing to trace the exact outer outline of the whole city. The brute force approach works by checking every single point from the very left edge of the city to the very right edge to see which building is tallest at that exact moment.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the absolute left edge of all the buildings combined.
  2. Check every single point as you move steadily toward the right edge.
  3. At each specific point you stop at, look at every single building to see which ones cover that point.
  4. From the buildings that cover that point, find the one with the highest roof.
  5. Write down the height of that tallest roof as part of your outline.
  6. Move slightly to the right and repeat the process of checking every building again.
  7. Once you reach the far right edge of the city, clean up your list of heights by removing any places where the height stayed the same so you are left with just the sharp corners of the skyline.

Code Implementation

def get_skyline(buildings):
    if not buildings:
        return []

    # Collect all unique x-coordinates from building edges to check every point
    all_x_coordinates = set()
    for building in buildings:
        all_x_coordinates.add(building[0])
        all_x_coordinates.add(building[1])

    sorted_x_coordinates = sorted(list(all_x_coordinates))
    raw_skyline_points = []

    for current_x in sorted_x_coordinates:
        current_max_height = 0
        for building in buildings:
            left_x, right_x, height = building
            if left_x <= current_x < right_x:
                if height > current_max_height:
                    current_max_height = height

        raw_skyline_points.append([current_x, current_max_height])

    # Append a trailing point to handle the ground level at the final right edge
    final_skyline_result = []
    previous_height = -1

    for point in raw_skyline_points:
        current_x, current_height = point
        if current_height != previous_height:
            final_skyline_result.append([current_x, current_height])
            previous_height = current_height

    return final_skyline_result

Big(O) Analysis

Time Complexity
O(n * W) – To trace the skyline, we iterate through every single point across the width of the city, let us call it W, representing the distance from the leftmost to the rightmost edge. At each of these W distinct coordinate points, we must evaluate all n buildings to determine which one has the highest roof. This results in checking n buildings for each of the W points, leading to approximately W * n operations. Simplifying this gives a time complexity of O(W * n), where W is the coordinate range and n is the number of buildings.
Space Complexity
O(N) – The auxiliary space is driven by the data structures needed to trace the outline, specifically the list of critical points and the tracking mechanism used to store active building heights as you move across the city. Let N represent the total number of buildings given in the input. In the worst-case scenario, every building introduces multiple coordinate events and gets stored in these intermediate structures simultaneously. Therefore, the extra memory scales linearly with the number of buildings, resulting in an overall space complexity of Big O of N.

Optimal Solution

Approach

Instead of looking at the entire city at once, the optimal approach is to scan across the landscape from left to right, processing every building edge as a distinct event. By maintaining a dynamic collection of currently active building heights, we can instantly determine whenever the overall silhouette of the skyline changes.

Here's how the algorithm would work step-by-step:

  1. Gather every single starting point and ending point for all the buildings, and sort them in order from left to right across the landscape.
  2. Keep track of the ground height as our baseline, and maintain a collection of all the building heights that are currently sheltering our current position.
  3. Walk across the sorted points from left to right, stopping at each point in turn.
  4. If we encounter the start of a building, add its height to our active collection.
  5. If we encounter the end of a building, remove its height from our active collection.
  6. At every stopping point, look at the tallest building currently in our active collection to find the highest point overhead.
  7. Compare this current highest point with the previously recorded skyline height; if there is a change, record this spot and the new height as a crucial turning point for our skyline.
  8. Continue this process until all points have been visited, resulting in a complete outline of the city profile.

Code Implementation

import heapq

class Solution:
    def getSkyline(self, buildings: list[list[int]]) -> list[list[int}}:
        event_points = []
        for left_coord, right_coord, building_height in buildings:
            event_points.append((left_coord, -building_height, right_coord))
            event_points.append((right_coord, building_height, 0))
        
        # Sorting coordinates ensures we sweep across the landscape from left to right.
        event_points.sort()
        
        skyline_result = []
        active_heights = [0]
        height_tracker = {0: 1}
        
        for current_x, current_height, ending_x in event_points:
            if current_height < 0:
                actual_height = -current_height
                active_heights.append(actual_height)
                heapq.heapify(active_heights)
                height_tracker[actual_height] = height_tracker.get(actual_height, 0) + 1
            else:
                height_tracker[current_height] -= 1
            
            # We clean up inactive heights to ensure the maximum reflects current buildings.
            while active_heights and height_tracker.get(active_heights[0], 0) == 0:
                removed_height = heapq.heappop(active_heights)
                if removed_height in height_tracker and height_tracker[removed_height] == 0:
                    del height_tracker[removed_height]
            
            current_max_height = active_heights[0]
            if not skyline_result or skyline_result[-1][1] != current_max_height:
                skyline_result.append([current_x, current_max_height])
        
        return skyline_result

Big(O) Analysis

Time Complexity
O(n log n) – For n buildings, extracting and sorting all 2n start and end events takes O(n log n) time. As we iterate through these 2n sorted events, updating our active height collection and querying the maximum height at each step takes logarithmic time using a heap or balanced search tree. Since this processing happens for each of the 2n events, it results in roughly 2n * log(2n) operations, which simplifies to O(n log n) overall.
Space Complexity
O(n) – Let N represent the number of buildings given in the input. The algorithm requires auxiliary space to store the critical events, where each of the N buildings generates two separate events for its start and end points, resulting in a sorted event list of size 2N. Additionally, the active height collection stores at most N heights simultaneously as we sweep across the landscape. Finally, the resulting skyline output list can store up to 2N key points in the worst-case scenario. Combining the event list, the active collection, and the output structure, the total extra memory scales linearly with the number of buildings, simplifying to Big O of N space complexity.

Edge Cases

Empty input array representing zero buildings
How to Handle:
Return an empty list immediately because no skyline can be formed without structures.
Single building input
How to Handle:
Add both the start-height and end-zero coordinates directly to the result list since there are no overlaps.
Buildings with identical left coordinates but different heights
How to Handle:
Sort the critical events so that taller buildings are processed first at the same x-coordinate.
Contiguous or overlapping buildings with the exact same height
How to Handle:
Track the maximum height dynamically using a max-heap and only emit a point when the max height actually changes.
Buildings with negative coordinates or heights
How to Handle:
Standardize sorting and heap operations correctly since coordinate values can span from negative to positive infinity.
Completely nested buildings where a smaller building is inside a taller one
How to Handle:
The max-heap naturally suppresses the inner building's height changes until the taller outer building's span ends.
Extremely large number of buildings causing performance bottlenecks
How to Handle:
Utilize an O(N log N) sweep-line algorithm with a balanced BST or max-heap to ensure efficient scaling.
Building bounds sharing exact edges where one ends and another begins
How to Handle:
Sort start points before end points, and start points of taller buildings before shorter ones at the same x-coordinate.