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.

The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:


	lefti is the x coordinate of the left edge of the ith building.
	righti is the x coordinate of the right edge of the ith building.
	heighti is the height of the ith building.


You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.

Note: 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],...]

&nbsp;
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:
Figure A shows the buildings of the input.
Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.


Example 2:

Input: buildings = [[0,2,3],[2,5,3]]
Output: [[0,3],[5,0]]


&nbsp;
Constraints:


	1 &lt;= buildings.length &lt;= 104
	0 &lt;= lefti &lt; righti &lt;= 231 - 1
	1 &lt;= heighti &lt;= 231 - 1
	buildings is sorted by lefti in&nbsp;non-decreasing order.


class Solution:
    def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:
        d = collections.defaultdict(list)
        
        for i,(start, end, height) in enumerate(buildings):
            d[start].append(height)
            d[end].append(-height)
            
        l = list(d.keys())
        l.sort()
        
        result = []
        
        active = []
        
        for key in l:
            o = d[key]
            o.sort(reverse=True)
            for j in o:
                if j > 0:
                    if not result or not active:
                        result.append([key, j])
                        active.append(j)
                    else:
                        if j > active[-1]:
                            result.append([key, j])
                            active.append(j)
                        else:
                            active.insert(bisect_left(active, j), j)
                else:
                    idx = active.index(-j)
                    if idx == len(active) - 1:
                        active.pop()
                        if active:
                            result.append([key, active[-1]])
                        else:
                            result.append([key, 0])
                    else:
                        active.pop(idx)
        
        return result
                        
class height implements Comparable<height>{
    int val = -1;
    int pos = -1;
    boolean isStart = false;
    height(int a, int b, boolean c){
        val = a;
        pos = b;
        isStart = c;
    }
    public int compareTo(height h){
        if(this.pos != h.pos)
            return this.pos-h.pos;
        if(isStart)
            return -1;
        if(h.isStart)
            return 1;
        
        return this.val-h.val;
    }
}
class Solution {
    public List<List<Integer>> getSkyline(int[][] buildings) {
        
        PriorityQueue<height> mQ = new PriorityQueue<>();
        int len = buildings.length;
        for(int[] b: buildings) {
            mQ.add(new height(b[2],b[0],true));
            mQ.add(new height(b[2],b[1],false));
        }
        PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
        heap.add(0);
        int prevHeight = 0;
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> lst;
        while(mQ.size()>0) {
            height h = mQ.poll();
            if(h.isStart){
                heap.offer(h.val);
            } else {
                heap.remove(h.val);
            }
            
            if(prevHeight != heap.peek()){
                lst = new ArrayList<>();
                lst.add(h.pos);
                
                if(res.size() > 0 && res.get(res.size()-1).get(0) == h.pos){
                    lst.add(Math.max(heap.peek(), res.get(res.size()-1).get(1)));
                    res.remove(res.size()-1);
                } else 
                    lst.add(heap.peek());
                res.add(lst);
                prevHeight = heap.peek();
            }
        }
        return res;
    }
}
/*
1.mark the starting and ending pt of each building
    -> let height of starting pt be negative and ending pt be positive   [2,4,10] -> [[2,-10],[4,10]]
2.mark all consecutive building
    ->store every pair of x and y in pair sort it acc to x
3.get max y for all x values
    ->use heap-->(multiset) to store all buildings, insert new height of building else erase buiding height
4.remove pts of same height and store ans in results
*/
class Solution {
public:
    vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
		//step1
        vector<pair<int,int>> coordinate;
        for(auto building: buildings){
            coordinate.push_back({building[0],-building[2]});
            coordinate.push_back({building[1],building[2]});
        }
		//step2
        sort(coordinate.begin(), coordinate.end());
        
		//step3
        multiset<int,greater<int>> pq = {0};
        vector<vector<int>> result;
        int prev = 0;
        for(auto p: coordinate){
            if (p.second<0) pq.insert(-p.second);
            else pq.erase(pq.find(p.second));
            int cur=*pq.begin();
            if (prev!=cur) {
                result.push_back({p.first,cur});
                prev=cur;
            }
        }
        return result;
    }
};
var getSkyline = function(buildings) {
    
    let results = [];
    
    let points = [];
    
    for (let building of buildings) {
        points.push([building[0],building[2]])
        points.push([building[1],-building[2]])
    }
    
    let heights = [];
    
    points.sort((a,b)=>(b[1]-a[1]))
    points.sort((a,b)=>(a[0]-b[0]))
    
    for (let point of points) {
        if(point[1] >0) {
            heights.push(point[1])
        }
        else {
            heights.splice(heights.indexOf(-point[1]),1)
        }
        let curHeight = (heights.length == 0?0:Math.max(...heights))
        
        if(results.length == 0 || results[results.length-1][1] != curHeight) results.push([point[0], curHeight]);
    }
    
    
    return results;
};
The Skyline Problem