K Closest Points to Origin

MediumHeap · Quickselect · Top K🧩 Heap & Top-KLeetCode #973 ↗Updated

Problem

Each entry of points is a 2-D point [x, y]. Return the k points with the smallest Euclidean distance to (0, 0), in any order. The set of answers is guaranteed to be unique.
Input[[1,3],[-2,2]], k=1Output[[-2,2]]
Input[[3,3],[5,-1],[-2,4]], k=2Output[[3,3],[-2,4]]

1 ≤ k ≤ n ≤ 104  ·  -104 ≤ x, y ≤ 104

Try it yourself

Java
class Solution {
    public int[][] kClosest(int[][] points, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Compare squared distances x² + y² (no sqrt, same order). And you never need the k points sorted — only separated from the rest, which is exactly what one partition step does.
PatternHeap & Top-K

Instinct "K largest / smallest / closest / most frequent", or "always take the best available next"? Keep a heap - size k for top-K, or a ready-queue for scheduling.

Memory hack Guard the top-K club with a bouncer - a min-heap of size k whose root is the weakest member; anyone stronger kicks them out.

Open the Heap & Top-K guide →

Approaches

Brute ForceSort All by Distance

Time O(n log n)Space O(log n) sort stack

Sort every point by squared distance and return the first k. Fully orders all n points even though only the first k matter.

Java
public int[][] kClosest(int[][] points, int k) {
    Arrays.sort(points, (a, b) ->
        Integer.compare(a[0] * a[0] + a[1] * a[1], b[0] * b[0] + b[1] * b[1]));
    return Arrays.copyOf(points, k);
}

One-liner and correct, but sorts far more than required.

At a glance

LevelApproachTimeSpace
Brute ForceSort All by DistanceO(n log n)O(log n) sort stack
BetterMax-Heap of Size kO(n log k)O(k)
OptimalQuickselect (Random Pivot)O(n) avg, O(n²) worstO(1)
Common pitfalls
  • Using a min-heap of size k — it evicts the closest points instead of the farthest.
  • Math.sqrt on doubles — slower and invites precision bugs; squares suffice.
  • Quickselect with a fixed pivot — O(n²) on sorted/adversarial input.
Interview tips
  • Ask whether output order matters — if not, you don't need to sort.
  • Contrast heap (streaming, O(k) memory) vs quickselect (in-place, needs all data).
  • Explain quickselect's expected O(n) via the halving geometric series.
Pattern
Top-k by key → size-k heap of the opposite kind, or quickselect when the data fits in memory.
My notes saved in this browser