Skip to content
DSA Patterns
Menu
Language
Sweep LineLC #2181 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

The Skyline Problem

Problem (restated)

Buildings are [left, right, height] axis-aligned rectangles on the ground. Return the skyline as key points [x, height]: every x where the silhouette height changes, in left-to-right order, ending at height 0.

Intuition

Sweep left to right. Each building is an enter at left (add height) and an exit at right (remove). The skyline only emits when the max active height changes. Tie-break at the same x: process enters before exits (a building starting where another ends should not dip to 0), and taller enters first.

Approaches

Sweep + active heights

Unverified
Time O(n log n)Space O(n)

Idea. Events (x, −h, id) start and (x, +h, id) end; sort. A live set + max-heap (lazy delete) of heights, plus a ground height 0. After all events at x, if max ≠ last emitted height, append [x, max].

Walkthrough. [[2,9,10],[3,7,15]] emits [2,10], then [3,15], then [7,10], then [9,0].

Trade-offs. Lazy heap deletion is the usual interview version. Removing from a real multiset is cleaner in C# (SortedDictionary). Sort key is the overlap rule: start-before-end at the same x.

Solution
Show helper code
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}
/** A real binary heap with a caller-supplied "less" comparator: O(log n) push/pop. */
class Heap<T> {
  private a: T[] = [];
  private less: (x: T, y: T) => boolean;
  constructor(less: (x: T, y: T) => boolean) {
    this.less = less;
  }
  get size(): number {
    return this.a.length;
  }
  peek(): T {
    return this.a[0]!;
  }
  push(x: T): void {
    const a = this.a;
    a.push(x);
    let i = a.length - 1;
    while (i > 0) {
      const p = (i - 1) >> 1;
      if (!this.less(a[i]!, a[p]!)) break;
      [a[i], a[p]] = [a[p]!, a[i]!];
      i = p;
    }
  }
  pop(): T {
    const a = this.a;
    const top = a[0]!;
    const last = a.pop()!;
    if (a.length) {
      a[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let s = i;
        if (l < a.length && this.less(a[l]!, a[s]!)) s = l;
        if (r < a.length && this.less(a[r]!, a[s]!)) s = r;
        if (s === i) break;
        [a[i], a[s]] = [a[s]!, a[i]!];
        i = s;
      }
    }
    return top;
  }
}
export function getSkyline(buildings: number[][]): number[][] {
  const events: [number, number, number][] = [];
  for (let i = 0; i < buildings.length; i++) {
    const [l, r, h] = buildings[i]!;
    events.push([l, -h, i]);
    events.push([r, h, i]);
  }
  events.sort((a, b) => a[0]! - b[0]! || a[1]! - b[1]! || a[2]! - b[2]!);
  const live = new Set<number>([-1]);
  // Real binary max-heap of [height, id]; the top is the tallest live building.
  const heap = new Heap<[number, number]>((a, b) => a[0]! > b[0]!);
  heap.push([0, -1]);
  const res: number[][] = [];
  let i = 0;
  while (i < events.length) {
    const x = events[i]![0]!;
    while (i < events.length && events[i]![0] === x) {
      const h = events[i]![1]!;
      const id = events[i]![2]!;
      if (h < 0) {
        live.add(id);
        heap.push([-h, id]);
      } else {
        live.delete(id);
      }
      i++;
    }
    // Lazy deletion: drop heap tops whose building is no longer live.
    while (heap.size && !live.has(heap.peek()[1]!)) heap.pop();
    const maxH = heap.peek()[0]!;
    if (!res.length || res[res.length - 1]![1] !== maxH) res.push([x, maxH]);
  }
  return res;
}
export function getSkyline(buildings: number[][]): number[][] {
  const events: [number, number, number][] = [];
  for (let i = 0; i < buildings.length; i++) {
    const [l, r, h] = buildings[i]!;
    events.push([l, -h, i]);
    events.push([r, h, i]);
  }
  events.sort((a, b) => a[0]! - b[0]! || a[1]! - b[1]! || a[2]! - b[2]!);
  const live = new Set<number>([-1]);
  // Real binary max-heap of [height, id]; the top is the tallest live building.
  const heap = new Heap<[number, number]>((a, b) => a[0]! > b[0]!);
  heap.push([0, -1]);
  const res: number[][] = [];
  let i = 0;
  while (i < events.length) {
    const x = events[i]![0]!;
    while (i < events.length && events[i]![0] === x) {
      const h = events[i]![1]!;
      const id = events[i]![2]!;
      if (h < 0) {
        live.add(id);
        heap.push([-h, id]);
      } else {
        live.delete(id);
      }
      i++;
    }
    // Lazy deletion: drop heap tops whose building is no longer live.
    while (heap.size && !live.has(heap.peek()[1]!)) heap.pop();
    const maxH = heap.peek()[0]!;
    if (!res.length || res[res.length - 1]![1] !== maxH) res.push([x, maxH]);
  }
  return res;
}

Template connection

Skyline shape of Sweep Line: enter/exit events, active set of heights, emit on max change. LC 253 is the same sweep with a count instead of a height multiset.

Reflection

  • A start is (x, -h) and an end is (x, +h). At the same x, the start sorts first. Processing the end first drops the height to the ground and emits a false point.
  • After every event at x, if the live maximum changed, write [x, max]. The ground height is 0. An end removes that building from the live set.
  • Overlapping roofs collapse to the max. Two adjacent buildings of the same height do not emit a point between them. An empty skyline writes nothing.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Skyline of [2,9,10] and [3,7,15]. Enter adds a height, exit removes; emit when the max changes.

h=10
h=15

events = left enter, right exit

Key:CurrentActive rangeMatchSettled