sagelearnai

K Closest Points to Origin

Difficulty: Medium · Pattern: Heap & Priority Queue · LeetCode #973

Given points [x, y] on a plane, return the k points closest to the origin (0, 0) by Euclidean distance. The answer is unique; return it in any order.

Examples

text
points = [[1, 3], [-2, 2], [5, -1]], k = 1   →  [[-2, 2]]
points = [[3, 3], [5, -1], [-2, 4]], k = 2   →  [[3, 3], [-2, 4]]

Hints

  1. Compare squared distances, x² + y²; no square root needed.
  2. To keep the k smallest, use a max-heap of size k and pop the farthest when it overflows.

Approach

Iterate over the points, pushing (−dist², point) into a heap (a max-heap by distance via negation). When the size exceeds k, pop the farthest point. The remaining k points are the closest. O(n log k). Quickselect on distances gives O(n) average.

Complexity

Time: O(n log k). Space: O(k).

Python solution
import heapq

def kClosest(points, k):
    h = []
    for x, y in points:
        heapq.heappush(h, (-(x * x + y * y), x, y))
        if len(h) > k:
            heapq.heappop(h)
    return [[x, y] for _, x, y in h]
JavaScript solution
class MinHeap {
  constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
  get size() { return this.a.length; }
  peek() { return this.a[0]; }
  push(x) { const a = this.a; a.push(x); let i = a.length - 1;
    while (i > 0) { const p = (i - 1) >> 1; if (this.cmp(a[i], a[p]) >= 0) break; [a[i], a[p]] = [a[p], a[i]]; i = p; } }
  pop() { const a = this.a, top = a[0], last = a.pop();
    if (a.length) { a[0] = last; let i = 0;
      for (;;) { const l = 2 * i + 1, r = l + 1; let m = i;
        if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
        if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
        if (m === i) break; [a[i], a[m]] = [a[m], a[i]]; i = m; } }
    return top; }
}

function kClosest(points, k) {
  const d = ([x, y]) => x * x + y * y;
  const h = new MinHeap((a, b) => d(b) - d(a));   // max-heap by distance
  for (const p of points) { h.push(p); if (h.size > k) h.pop(); }
  return h.a;
}