AlgoMaster Logo

The Skyline Problem

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Sorted Edges + Priority Queue

Intuition:

The Skyline problem is essentially about managing the heights of buildings as you move from left to right across the plane. The key idea is to focus on the "critical points" where the height changes. These critical points are either the start or end of a building. By sorting these events and using a priority queue to track current buildings, we can determine the skyline at each step.

Steps:

  1. Extract critical points from the input buildings. Each building provides two points: its starting event and its end event. The start of a building contributes a positive height and the end contributes a negative height.
  2. Sort the events:
    • By the x-coordinate (starting position).
    • In case of ties, prioritize by height. If it's a start point, sort from high to low; if it's an end point, sort from low to high.
  3. Use a max-heap (priority queue) to keep track of all active building heights. The maximum height in the heap represents the current tallest building that influences the skyline.
  4. Iterate through the sorted events:
    • When adding a start event, add its height to the heap.
    • When processing an end event, remove its height from the heap.
    • Check if the current max height (top of the heap) changes before and after processing the event. If it does, add the new key point to the result.
  5. Return the list of key points as the skyline.

Code: