Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: The Skyline Problem

Posted on August 5, 2019July 26, 2020 by braindenny

The Skyline Problem



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #heap, #linesweep

A city’s skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

Leetcode: The Skyline Problem

Leetcode: The Skyline Problem

Buildings Skyline Contour
The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 <= Li, Ri <= INT_MAX, 0 < Hi <= INT_MAX, and Ri – Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .

The output is a list of “key points” (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], … ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.

For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].

Notes:

  • The number of buildings in any input list is guaranteed to be in the range [0, 10000].
  • The input list is already sorted in ascending order by the left x position Li.
  • The output list must be sorted by the x position.
  • There must be no consecutive horizontal lines of equal height in the output skyline. For instance, […[2 3], [4 5], [7 5], [11 5], [12 7]…] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: […[2 3], [4 5], [12 7], …]

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
## https://code.dennyzhang.com/the-skyline-problem
## Basic Ideas: line sweep
##
##  (s, e):
##    s: start a region
##    e: end a region
##
##  Each point would change the height of the building
##
##  When region starts, it may increase the height. 
##        Then we have a new point
##
##  When region ends, it may decrease the height.
##        If it decreases, we have a new point.
##        But how we know whether it will decrease?
##
## Complexity: Time O(n*n), Space O(n)
import heapq
class Solution:
    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        points = []
        for i, b in enumerate(buildings):
            points.append([b[0], -b[2]]) # start
            points.append([b[1], b[2]]) # end
        points.sort()

        l = []
        # change value to negative to acheive max heap
        heapq.heapify(l)

        # add a dummy height to avoid hitting the ground
        heapq.heappush(l, 0)
        maxH = 0
        res = []
        for p in points:
            if p[1] < 0:
                # push the close point
                heapq.heappush(l, p[1])
            else:
                # close current range
                for i, v in enumerate(l):
                    if v == -p[1]:
                        del l[i]
                        heapq.heapify(l)
                        break
            # peek
            if len(l) > 0 and maxH != l[0]:
                maxH = l[0]
                res.append([p[0], -maxH])
        return res
linkedin
github
slack

Post Views: 0
Posted in HardTagged #heap, linesweep

Post navigation

LeetCode: Minimum Number of Taps to Open to Water a Garden
Series: Line Sweep Problems & Follow-up

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.