
Problem
Solution
Submissions
The Skyline Problem
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to solve the skyline 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.
Each building is represented by a triplet of integers [left, right, height], where:
- left is the x coordinate of the left edge of the building.
- right is the x coordinate of the right edge of the building.
- height is the height of the building.
The skyline should be represented as a list of "key points" sorted by their x-coordinate in ascending order. Each key point is a pair of integers [x, height], where:
- x is the x-coordinate of a key point.
- height is the height of the skyline at that point.
Example 1
- 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:
- At x=2, the first building starts with height 10, so we have point [2,10].
- At x=3, the second building starts with height 15, so the maximum height becomes 15, giving us [3,15].
- At x=7, the second building ends, leaving the third building with height 12, so we have [7,12].
- At x=12, the third building ends, and there's no building, so the height becomes 0, giving us [12,0].
- At x=15, the fourth building starts with height 10, so we have [15,10].
- At x=20, the fourth building ends and the fifth building is still present with height 8, so we have [20,8].
- At x=24, the fifth building ends, making the height 0, so we have [24,0].
Example 2
- Input: buildings = [[0,2,3],[2,5,3]]
- Output: [[0,3],[5,0]]
- Explanation:
- At x=0, the first building starts with height 3, so we have point [0,3].
- At x=2, the first building ends and the second building starts, but both have the same height of 3, so there's no change in skyline.
- At x=5, the second building ends, making the height 0, so we have [5,0].
Constraints
- 1 ≤ buildings.length ≤ 10^4
- 0 ≤ left < right ≤ 2^31 - 1
- 1 ≤ height ≤ 2^31 - 1
- buildings is sorted by left in ascending order
- Time Complexity: O(n log n) where n is the number of buildings
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a priority queue to keep track of the highest building at each point
- Process building edges (start and end) in ascending order of x-coordinate
- Use a height map to keep track of building heights for each start and end point
- For each critical point (where a building starts or ends), recalculate the maximum height
- Only add a point to the result when there's a change in the maximum height