Skip to Content

Skyline Line Sweep

Home | Coding Interviews | Miscellaneous | Skyline Line Sweep

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],...]

import sortedcontainers
class Solution:
    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        events = []
        for i in buildings:
            events.append((0, i[0], i[2]))
            events.append((1, i[1], i[2]))
            
        events = sorted(events, key = lambda x:(x[1], x[0], -x[2] if x[0] == 0 else x[2]))
        
        # print(events)
        
        result = []
        current_hegihts = sortedcontainers.SortedList([0])
        
        for e in events:
            event_type, index, height = e
            # print(e, current_hegihts)
            if event_type == 0: # start 
                if height > current_hegihts[-1]:
                    result.append([index, height])
                current_hegihts.add(height)
            else:
                current_hegihts.remove(height)
                # print(current_hegihts)
                if height > current_hegihts[-1]:
                    result.append([index, current_hegihts[-1]])
        return result

There are also solutions using heaps/priority queues

class Solution(object):
    def getSkyline(self, buildings):
        """
        :type buildings: List[List[int]]
        :rtype: List[List[int]]
        """
        
        buildings.sort(key=lambda x:[x[0],-x[2]])    #Sort elements according to x-axis (ascending) and height(descending)
        new_b=[]
        max_r=-float('inf')
        min_l=float('inf')
        for i in buildings:
            new_b.append([-i[2],i[0],i[1]])    #Create new array for priority queue with [-1*height, left,right], as we are creating max heap
            max_r=max(max_r,i[1])
            min_l=min(min_l,i[0])
            
        ans=[[0,0,max_r+1]]              #for default when the buildings at a specific point is over
        f_ans=[]
        heapq.heapify(ans)
        while min_l<=max_r:
            while new_b and min_l>=new_b[0][1]: 
                temp=new_b.pop(0)
                heapq.heappush(ans,temp)
            while ans and ans[0][2]<=min_l:
                heapq.heappop(ans)
                
            if not f_ans or f_ans[-1][1]!=(-ans[0][0]):
                f_ans.append([min_l,-ans[0][0]])
            if new_b:
                min_l=min(ans[0][2],new_b[0][1])     #To update the min_l according to the next element and the element itself
            else:
                min_l=ans[0][2]
            
        return f_ans

Posted by Jamie Meyer 15 days ago