Tutorialspoint
Problem
Solution
Submissions

Skyline Problem

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the skyline formed by a set of rectangular buildings. Given an array of buildings where buildings[i] = [left, right, height], return the skyline formed by these buildings. The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,h1],[x2,h2],...] where each key point is the left endpoint of some horizontal segment in the skyline except the last point which marks the end.

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:
    • Building [2,9,10] creates skyline from x=2 to x=9 with height 10.
    • Building [3,7,15] overlaps and has greater height, creating key point [3,15].
    • At x=7, height drops back to 12, then to 0 at x=12.
    • Subsequent buildings create more key points as heights change.
Example 2
  • Input: buildings = [[0,2,3],[2,5,3]]
  • Output: [[0,3],[5,0]]
  • Explanation:
    • First building creates skyline from x=0 to x=2 with height 3.
    • Second building continues the same height from x=2 to x=5.
    • Since heights are same, no key point needed at x=2.
    • Final key point at x=5 marks end with height 0.
Constraints
  • 1 ≤ buildings.length ≤ 10^4
  • 0 ≤ left < right ≤ 2^31 - 1
  • 1 ≤ height ≤ 2^31 - 1
  • Buildings are sorted by left coordinate
  • Time Complexity: O(n^2)
  • Space Complexity: O(n)
ArraysData StructureGoogleeBay
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a sweep line algorithm to process building start and end events
  • Create events for building starts (negative height) and ends (positive height)
  • Sort events by x-coordinate, handling ties appropriately
  • Use a data structure to track active building heights at each x-coordinate
  • When height changes, add a key point to the result

Steps to solve by this approach:

 Step 1: Create events for each building - start event (x, height, 0) and end event (x, height, 1).
 Step 2: Sort events by x-coordinate with proper tie-breaking rules for overlapping events.
 Step 3: Process events in order, maintaining a list of active building heights.
 Step 4: For start events, add the building height to active heights list.
 Step 5: For end events, remove the corresponding height from active heights list.
 Step 6: After each event, find the maximum height among active buildings.
 Step 7: If maximum height changes, add a key point [x, newMaxHeight] to the result.

Submitted Code :