InterviewPrepKit

Home / Coding / Heap & Priority Queue

K Closest Points to Origin

medium Original ↗
Solving tips
  • Compare squared distance x²+y² — it preserves the ordering with no floats or square roots.
  • For k smallest, keep a MAX-heap of size k (negate in Python) so the root is the current farthest and can be evicted when a closer point arrives.
  • Know the full ladder: sort O(n log n), size-k heap O(n log k), quickselect average O(n) with randomized 3-way partition for duplicate distances.
  • Pick heap when k << n or data streams; pick quickselect when the array is in hand and mutation/order-within-answer is fine.

Problem

Given a list of points on the plane, points[i] = [x_i, y_i], and an integer k, return the k points closest to the origin (0, 0) by Euclidean distance sqrt(x² + y²).

The answer may be returned in any order. The answer is guaranteed to be unique (no distance ties straddle the k-th place).

Examples

  • points = [[1, 3], [-2, 2]], k = 1[[-2, 2]] — distances are √10 ≈ 3.16 and √8 ≈ 2.83, so [-2, 2] is closer.
  • points = [[3, 3], [5, -1], [-2, 4]], k = 2[[3, 3], [-2, 4]] (any order) — squared distances 18, 26, 20; the two smallest are 18 and 20.
  • points = [[0, 1], [1, 0]], k = 2[[0, 1], [1, 0]] — asking for all points returns all points.

Constraints

  • 1 <= k <= len(points) <= 10^4
  • -10^4 <= x_i, y_i <= 10^4

Think about it first

Hint 1 You only need the *ordering* of distances, never the distances themselves — comparing `x² + y²` gives the same order as comparing `sqrt(x² + y²)`, with no floats.
Hint 2 Sorting all n points works in O(n log n), but you're only asked for k of them. When streaming through the points, what fixed-size structure lets you keep "the k best so far" and evict the current worst in O(log k)?
Hint 3 Max-heap of size k keyed on squared distance (negate for Python): push each point, pop whenever size exceeds k — O(n log k). And if the interviewer pushes for average O(n), partition the array around a pivot distance à la quickselect until the split lands exactly at k.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.