973. K Closest Points to Origin
Asked at 16Meta77Amazon48Apple30Google27Bloomberg25Microsoft23Airbnb38Asana100Wix87Whatnot63Swiggy59Axon51Salesforce35LinkedIn27Oracle27Goldman Sachs21
Problem
Return the k points closest to the origin (by Euclidean distance), in any order. The answer is unique up to order.
Example: points = [[3,3],[5,-1],[-2,4]], k = 2 → [[3,3],[-2,4]]
Constraints: up to 10⁴ points.
Keep a max-heap of size k on squared distance; evict the farthest. (Quickselect gives average O(n).)
Complexity: O(n log k).
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
h = []
for x, y in points:
heappush(h, (-(x * x + y * y), x, y))
if len(h) > k:
heappop(h)
return [[x, y] for _, x, y in h]
assert Solution().kClosest([[1, 3], [-2, 2]], 1) == [[-2, 2]]
assert sorted(Solution().kClosest([[3, 3], [5, -1], [-2, 4]], 2)) == [[-2, 4], [3, 3]]
class Solution {
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (b[0] * b[0] + b[1] * b[1]) - (a[0] * a[0] + a[1] * a[1]));
for (int[] p : points) {
pq.add(p);
if (pq.size() > k) pq.poll();
}
return pq.toArray(new int[0][]);
}
}
type point struct{ d, x, y int }
type pointHeap []point // max-heap by distance
func (h pointHeap) Len() int { return len(h) }
func (h pointHeap) Less(i, j int) bool { return h[i].d > h[j].d }
func (h pointHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *pointHeap) Push(x any) { *h = append(*h, x.(point)) }
func (h *pointHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func kClosest(points [][]int, k int) [][]int {
h := &pointHeap{}
for _, p := range points {
heap.Push(h, point{p[0]*p[0] + p[1]*p[1], p[0], p[1]})
if h.Len() > k { // drop the farthest
heap.Pop(h)
}
}
res := [][]int{}
for _, p := range *h {
res = append(res, []int{p.x, p.y})
}
return res
}