#218

The Skyline Problem

Hard
ArrayDivide and ConquerBinary Indexed TreeSegment TreeSweep LineSortingHeap (Priority Queue)Ordered SetSweep LinePriority QueueSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution uses a sweep line algorithm with a priority queue to efficiently track the heights of buildings as we process events (start and end of buildings). This allows us to dynamically update the maximum height at each x-coordinate.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a list of all start and end points of buildings, marking starts with negative heights.
  2. 2Step 2: Sort the points by x-coordinate, and by height for ties.
  3. 3Step 3: Use a max-heap (priority queue) to keep track of current building heights.
  4. 4Step 4: Iterate through the sorted points, updating the heap and recording changes in height.
solution.py26 lines
1# Full working Python code
2from collections import defaultdict
3import heapq
4
5def getSkyline(buildings):
6    points = []
7    for left, right, height in buildings:
8        points.append((left, -height))  # Start of a building
9        points.append((right, height))   # End of a building
10    points.sort()
11    result = []
12    heights = [(0, 1)]  # (height, count)
13    prev_height = 0
14
15    for x, h in points:
16        if h < 0:
17            heapq.heappush(heights, (h, 1))
18        else:
19            heights.remove((h, 1))
20            heapq.heapify(heights)
21        current_height = -heights[0][0]
22        if current_height != prev_height:
23            result.append([x, current_height])
24            prev_height = current_height
25    return result
26

Complexity note: The sorting of points takes O(n log n) time, and maintaining the max-heap for heights takes O(log n) for each insertion/removal, leading to an overall efficient solution.

  • 1The skyline problem requires understanding how to manage overlapping intervals efficiently.
  • 2Using a max-heap allows for dynamic height tracking as buildings start and end.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.