K Closest Points to Origin
The drill: Pick the k points nearest the origin out of a scattered set — nearest meaning straight-line distance, no fixed order required among the ones you return.
A scattered set of 2D points arrives along with a count k, and the job is picking out the k points that sit closest to the origin.
Closeness means ordinary straight-line distance, and the k returned points can come back in any order among themselves — nothing about their relative sequence gets checked.
Ties at the boundary distance resolve however the picking method naturally breaks them, since any valid set of k closest points is accepted.
- point counts run up to several thousand
- coordinates can be negative, zero, or positive
- k never exceeds the number of points supplied
- the k returned points may come back in any order
HINT 1 THE NUDGE
Distance never needs a square root here — comparing squared distances puts points in the exact same order without ever calling sqrt.
HINT 2 THE STRUCTURE
Sorting every point by distance and slicing the first k works, but the far-away points still get fully sorted even though nobody asked about their order.
HINT 3 ONE STEP FROM THE ANSWER
Keep a max-heap capped at size k, keyed by squared distance. Push each point in, evict the current farthest whenever the heap overflows past k — what's left are the k closest.
k=2. Keep a max-heap capped at size 2, keyed by squared distance — the farthest point gets evicted whenever it overflows.
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
heap = [] # max-heap of size k, via negated distance
for x, y in points:
d = x * x + y * y
heapq.heappush(heap, (-d, x, y))
if len(heap) > k:
heapq.heappop(heap)
return [[x, y] for _, x, y in heap]class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
ordered = sorted(points, key=lambda p: p[0] * p[0] + p[1] * p[1])
return ordered[:k]class Solution {
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> heap =
new PriorityQueue<>((a, b) -> (b[0] * b[0] + b[1] * b[1]) - (a[0] * a[0] + a[1] * a[1]));
for (int[] p : points) {
heap.offer(p);
if (heap.size() > k) {
heap.poll();
}
}
return heap.toArray(new int[heap.size()][]);
}
}class Solution {
public int[][] kClosest(int[][] points, int k) {
int[][] sorted = points.clone();
Arrays.sort(sorted, (a, b) -> (a[0] * a[0] + a[1] * a[1]) - (b[0] * b[0] + b[1] * b[1]));
return Arrays.copyOfRange(sorted, 0, k);
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED