The Skyline Problem — LeetCode 218 Python Solution
- Problem
- #218
- Pattern
- Heap / Priority Queue
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
from queue import PriorityQueue
class Solution:
def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
skys, lines, pq = [], [], PriorityQueue()
for build in buildings:
lines.extend([build[0], build[1]])
lines.sort()
city, n = 0, len(buildings)
for line in lines:
while city < n and buildings[city][0] <= line:
pq.put([-buildings[city][2], buildings[city][0], buildings[city][1]])
city += 1
while not pq.empty() and pq.queue[0][2] <= line:
pq.get()
high = 0
if not pq.empty():
high = -pq.queue[0][0]
if len(skys) > 0 and skys[-1][1] == high:
continue
skys.append([line, high])
return skysComplexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 218. The Skyline Problem is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 218. The Skyline Problem?
- LeetCode 218. The Skyline Problem is rated Hard on LeetCode.
- What is the time complexity of LeetCode 218. The Skyline Problem?
- The Python solution on this page runs in O(n log n).
- What is the space complexity of LeetCode 218. The Skyline Problem?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 218. The Skyline Problem cover?
- LeetCode 218. The Skyline Problem is tagged Binary Indexed Tree, Segment Tree, Array, Divide and Conquer, Ordered Set, Sorting, Line Sweep and Heap (Priority Queue) on LeetCode.