## The Skyline Problem

`Sweep Line`, `Heap`, `Segment Tree`, `Binary Indexed Tree`

Hard

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).

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], ...]`

## Solution & Analysis

#### Sweep Line + Priority Queue

pq.remove()是O(n) time, 因此相比之下用TreeMap可以获得O(logn)的remove()时间复杂度

158 ms

``````class Solution {
public List<int[]> getSkyline(int[][] buildings) {
List<int[]> result = new ArrayList<>();
List<int[]> heights= new ArrayList<>();

for (int[] building: buildings) {
}

Collections.sort(heights, (a, b) -> {
if (a[0] == b[0]) {
return a[1] - b[1];
}
return a[0] - b[0];
});

PriorityQueue<Integer> pq = new PriorityQueue<Integer>((a, b) -> b - a);
pq.offer(0);
int prev = 0;
for (int[] h: heights) {
if (h[1] < 0) {
pq.offer(-h[1]);
} else {
pq.remove(h[1]);
}
int cur = pq.peek();
if (cur != prev) {
prev = cur;
}
}
return result;
}
}
``````

#### Sweep Line + TreeMap (Time complexity improved compare to Priority Queue)

``````public class Solution {
public List<int[]> getSkyline(int[][] buildings) {
List<int[]> heights = new ArrayList<>();
for (int[] b: buildings) {
}
Collections.sort(heights, (a, b) -> (a[0] == b[0]) ? a[1] - b[1] : a[0] - b[0]);
TreeMap<Integer, Integer> heightMap = new TreeMap<>(Collections.reverseOrder());
heightMap.put(0,1);
int prevHeight = 0;
for (int[] h: heights) {
if (h[1] < 0) {
Integer cnt = heightMap.get(-h[1]);
cnt = ( cnt == null ) ? 1 : cnt + 1;
heightMap.put(-h[1], cnt);
} else {
Integer cnt = heightMap.get(h[1]);
if (cnt == 1) {
heightMap.remove(h[1]);
} else {
heightMap.put(h[1], cnt - 1);
}
}
int currHeight = heightMap.firstKey();
if (prevHeight != currHeight) {
prevHeight = currHeight;
}
}
return skyLine;
}
}
``````

2 ms

``````class Solution {
class KeyPoint {
public int key;
public int height;
public KeyPoint next = null;

public KeyPoint(int key, int height) {
this.key = key;
this.height = height;
}
}
public List<int[]> getSkyline(int[][] buildings) {
List<int[]> res = new ArrayList<>();
KeyPoint dummy = new KeyPoint(-1, 0); // dummy head
KeyPoint pre = dummy;

for (int[] bd : buildings) {
int L = bd[0];
int R = bd[1];
int H = bd[2];

while (pre.next != null && pre.next.key <= L)
pre = pre.next;

int preH = pre.height;

if (pre.key == L)
pre.height = Math.max(pre.height, H);
else if (pre.height < H) {
KeyPoint next = pre.next;
pre.next = new KeyPoint(L, H);
pre = pre.next;
pre.next = next;
}

KeyPoint preIter = pre;
KeyPoint curIter = pre.next;
while (curIter != null && curIter.key < R) {
preH = curIter.height;
curIter.height = Math.max(curIter.height, H);

if (curIter.height == preIter.height)
preIter.next = curIter.next;
else
preIter = curIter;

curIter = curIter.next;
}

if (preIter.height != preH && preIter.key != R && (curIter == null || curIter.key != R)) {
KeyPoint next = preIter.next;
preIter.next = new KeyPoint(R, preH);
preIter.next.next = next;
}
}

KeyPoint first = dummy;
KeyPoint second = dummy.next;
while (second != null) {
if (second.height != first.height)
first = first.next;
second = second.next;
}
return res;
}
}
``````

#### Segment Tree

34 ms

``````class Solution {
public class Node {
Node left, right;
int start, end, height;
public Node(int start, int end) {
this.start = start;
this.end = end;
height = 0;
}
}

public List<int[]> getSkyline(int[][] buildings) {
List<int[]> result = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int[] b : buildings){
}
List<Integer> positions = new ArrayList<>(set);
Collections.sort(positions);
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < positions.size(); i++){
map.put(positions.get(i), i);
}
Node root = buildTree(0, positions.size() - 1);
for (int[] b : buildings){
}

explore(result, positions, root);
if(positions.size() > 0){
}
return result;
}

public Node buildTree(int start, int end) {
if (start > end){
return null;
}
Node root = new Node(start, end);
if (start + 1 < end){
int mid = (start + end) / 2;
root.left = buildTree(start, mid);
root.right = buildTree(mid, end);
}
return root;
}

public void add(Node root, int start, int end, int height) {
if (root == null || start >= root.end || end <= root.start || root.height > height){
return;
}
if (root.left == null && root.right == null){
root.height = height;
} else {
root.height = Math.min(root.left.height, root.right.height);
}
}

public void explore(List<int[]> result, List<Integer> positions, Node node){
if(node == null){
return;
}
if(node.left == null && node.right == null && (result.size() == 0 || result.get(result.size() - 1)[1] != node.height)){
}else{
explore(result, positions, node.left);
explore(result, positions, node.right);
}
}
}
``````

#### Divide and Conquer

5 ms, faster than 99.22%, 42.8 MB, less than 89.42%

We can find Skyline in Θ(nLogn) time using Divide and Conquer. The idea is similar to Merge Sort, divide the given set of buildings in two subsets. Recursively construct skyline for two halves and finally merge the two skylines.

Time complexity of above recursive implementation is same as Merge Sort. T(n) = T(n/2) + Θ(n) Solution of above recurrence is Θ(nLogn)

How to Merge two Skylines?

The idea is similar to merge of merge sort, start from first strips of two skylines, compare x coordinates. Pick the strip with smaller x coordinate and add it to result. The height of added strip is considered as maximum of current heights from skyline1 and skyline2.

``````public class Solution {
public List<int[]> getSkyline(int[][] buildings) {
if (buildings.length == 0)
return recurSkyline(buildings, 0, buildings.length - 1);
}

private LinkedList<int[]> recurSkyline(int[][] buildings, int p, int q) {
if (p < q) {
int mid = p + (q - p) / 2;
return merge(recurSkyline(buildings, p, mid),
recurSkyline(buildings, mid + 1, q));
} else {
rs.add(new int[] { buildings[p][0], buildings[p][2] });
rs.add(new int[] { buildings[p][1], 0 });
return rs;
}
}

int h1 = 0, h2 = 0;
while (l1.size() > 0 && l2.size() > 0) {
int x = 0, h = 0;
if (l1.getFirst()[0] < l2.getFirst()[0]) {
x = l1.getFirst()[0];
h1 = l1.getFirst()[1];
h = Math.max(h1, h2);
l1.removeFirst();
} else if (l1.getFirst()[0] > l2.getFirst()[0]) {
x = l2.getFirst()[0];
h2 = l2.getFirst()[1];
h = Math.max(h1, h2);
l2.removeFirst();
} else {
x = l1.getFirst()[0];
h1 = l1.getFirst()[1];
h2 = l2.getFirst()[1];
h = Math.max(h1, h2);
l1.removeFirst();
l2.removeFirst();
}
if (rs.size() == 0 || h != rs.getLast()[1]) {
rs.add(new int[] { x, h });
}
}
return rs;
}
}
``````

Divide and Conquer 6ms

``````class Solution {

public List<int[]> getSkyline(int[][] b) {
return helper(b, 0, b.length - 1);
}

List<int[]> helper(int[][] b, int s, int e) {
if(s > e) return new ArrayList<>();
if(s == e) {
List<int[]> res = new ArrayList<>();
return res;
}
int mid = s + (e - s)/2;
return mergeSkyline(helper(b, s, mid), helper(b, mid + 1, e));
}

List<int[]> mergeSkyline(List<int[]> a, List<int[]> b) {
List<int[]> res = new ArrayList<>();
int cur_h = 0, cur_h1 = 0, cur_h2 = 0, i1 = 0, i2 = 0;
while(i1 < a.size() && i2 < b.size()) {
int[] na = a.get(i1), nb = b.get(i2);
int x = -1;
if(na[0] < nb[0]) {
cur_h = Math.max(cur_h2, na[1]);
x = na[0];
cur_h1 = na[1];
i1++;
} else if(na[0] > nb[0]) {
cur_h = Math.max(cur_h1, nb[1]);
x = nb[0];
cur_h2 = nb[1];
i2++;
} else {
cur_h = Math.max(na[1], nb[1]);
x = nb[0];
cur_h1 = na[1];
cur_h2 = nb[1];
i1++;
i2++;
}
if(res.size() > 0 && res.get(res.size() - 1)[1] == cur_h) continue;
}