Skip to content
DSA Patterns
Menu
Language
Heap & Top KLC #9736 of 6← Previous

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

K Closest Points to Origin

Problem (restated)

Given points on a plane and integer k, return the k points closest to (0,0). Order among answers may vary.

Intuition

Track the k nearest with a max-heap keyed by squared distance (avoid sqrt).

Approaches

Max-heap of size k

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

Idea. Push each point; if heap size > k, pop farthest. Remaining heap is the answer multiset.

Walkthrough. [[1,3],[-2,2]], k=1 → [[-2,2]].

Trade-offs. Full sort is O(n log n); heap wins when k ≪ n. Quickselect is average O(n).

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 kClosest(points: number[][], k: number): number[][] {
  const dist = (p: number[]) => p[0]! * p[0]! + p[1]! * p[1]!;
  // Real binary max-heap of size k by distance; its top is the farthest kept point.
  const heap = new Heap<number[]>((a, b) => dist(a) > dist(b));
  for (const p of points) {
    if (heap.size < k) {
      heap.push(p);
    } else if (dist(p) < dist(heap.peek())) {
      heap.pop();
      heap.push(p);
    }
  }
  const res: number[][] = [];
  while (heap.size) res.push(heap.pop());
  return res;
}
export function kClosest(points: number[][], k: number): number[][] {
  const dist = (p: number[]) => p[0]! * p[0]! + p[1]! * p[1]!;
  // Real binary max-heap of size k by distance; its top is the farthest kept point.
  const heap = new Heap<number[]>((a, b) => dist(a) > dist(b));
  for (const p of points) {
    if (heap.size < k) {
      heap.push(p);
    } else if (dist(p) < dist(heap.peek())) {
      heap.pop();
      heap.push(p);
    }
  }
  const res: number[][] = [];
  while (heap.size) res.push(heap.pop());
  return res;
}

Template connection

Top-k heap ordered by distance, farthest at the root. Push every point. When the size passes k, pop the farthest. The points left in the heap are the answer, in any order.

Reflection

  • Squared distance is enough. A square root does not change the order. A max-heap of size k drops the farthest point.
  • On a tie, which point you keep is free. k == n returns every point. k == 1 returns the nearest.
  • (0, 0) has distance 0. Squaring a negative coordinate drops the sign.
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

k=2 closest to origin among (1,3), (-2,2), (2,-2). Max-heap of size k keyed by d².

(0,0)origin(1,3)(-2,2)(2,-2)

d² = x² + y²

Key:CurrentActive rangeMatchSettledEliminated