***The Skyline Problem (Leetcode 218)
Problem Link: https://leetcode.com/problems/the-skyline-problem/
import heapq
class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
arr=[]
for i in buildings:
arr.append([i[0],-i[2]])
arr.append([i[1],i[2]])
arr.sort(key=lambda x:(x[0],x[1]))
prevHeight=0
ans=[]
pq=[]
for i in range(len(arr)):
x=arr[i][0]
# If starting point,
# add to the maxheap
if(arr[i][1]<0):
# Since, it is a maxheap,
# insert -ve values
heapq.heappush(pq,arr[i][1])
else:
# If it is the end of building
for j in range(len(pq)):
if(-1*pq[j]==arr[i][1]):
break
del pq[j]
heapq.heapify(pq)
# Add to the ans[] when height changes
if(len(pq)>0):
if(prevHeight!=-1*pq[0]):
ans.append([x,-1*pq[0]])
prevHeight=-1*pq[0]
else:
if(prevHeight!=0):
ans.append([x,0])
prevHeight=0
return ans
Last updated