K closest points to the origin

Find the k points closest to the origin by keeping a max-heap of size k, evicting the farthest point whenever the heap grows too large.

Time O(n log k)Space O(k)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

A max-heap of size k keeps the k points with the smallest distances seen so far — not because you want the farthest first, but because the farthest of the kept set is the first one to evict if a closer point turns up. Comparing squared distances avoids an unnecessary square root while keeping the same order.

Code

public static List<(int x, int y)> KClosest(int[] xs, int[] ys, int k) {
    var heap = new PriorityQueue<int, int>(Comparer<int>.Create((p, q) => q - p)); // max-heap by distance
    for (int i = 0; i < xs.Length; i++) {
        int dist = xs[i] * xs[i] + ys[i] * ys[i];
        heap.Enqueue(i, dist);
        if (heap.Count > k) heap.Dequeue();
    }
    var result = new List<(int, int)>();
    while (heap.Count > 0) { int i = heap.Dequeue(); result.Add((xs[i], ys[i])); }
    return result;
}
static List<int[]> kClosest(int[] xs, int[] ys, int k) {
    PriorityQueue<int[]> heap = new PriorityQueue<>((p, q) -> q[1] - p[1]); // max-heap of {index, distance}
    for (int i = 0; i < xs.length; i++) {
        int dist = xs[i] * xs[i] + ys[i] * ys[i];
        heap.offer(new int[]{i, dist});
        if (heap.size() > k) heap.poll();
    }
    List<int[]> result = new ArrayList<>();
    while (!heap.isEmpty()) { int i = heap.poll()[0]; result.add(new int[]{xs[i], ys[i]}); }
    return result;
}
vector<pair<int, int>> kClosest(const vector<int>& xs, const vector<int>& ys, int k) {
    priority_queue<pair<int, int>> heap; // max-heap of {distance, index}
    for (int i = 0; i < (int)xs.size(); i++) {
        int dist = xs[i] * xs[i] + ys[i] * ys[i];
        heap.push({dist, i});
        if ((int)heap.size() > k) heap.pop();
    }
    vector<pair<int, int>> result;
    while (!heap.empty()) { int i = heap.top().second; heap.pop(); result.push_back({xs[i], ys[i]}); }
    return result;
}
import heapq

def k_closest(xs: list[int], ys: list[int], k: int) -> list[tuple[int, int]]:
    heap = []  # max-heap by distance (distances stored negated)
    for i in range(len(xs)):
        dist = xs[i] * xs[i] + ys[i] * ys[i]
        heapq.heappush(heap, (-dist, i))
        if len(heap) > k: heapq.heappop(heap)
    result = []
    while heap: _, i = heapq.heappop(heap); result.append((xs[i], ys[i]))
    return result

Tips

In the .NET library

Sorting all n points by distance costs O(n log n); the heap approach costs O(n log k), which wins decisively once k is much smaller than n.