Algo-Sim › Heaps & Priority Queues

K Closest Points to Origin

Medium · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input

Keep a max-heap of the k closest points by squared distance; anything farther than its top is evicted.

Problem

Given an array of points where points[i] = [x, y] and an integer k, return the k points closest to the origin (0, 0) by Euclidean distance. The answer is unique; return it in any order.

Constraints

Edge cases to test

Follow-up questions

Why squared distance?
It orders points the same way as the real distance without a square root, and stays exact in integers.
Can it be O(n)?
Quickselect on distance: O(n) on average, and the k closest come out unsorted.

Solution

Java

public int[][] kClosest(int[][] points, int k) {
    // Max-heap by squared distance: the farthest of the k kept sits on top.
    PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(dist(b), dist(a)));
    for (int[] p : points) {
        heap.offer(p);
        if (heap.size() > k) heap.poll();
    }
    int[][] result = new int[k][];
    for (int i = k - 1; i >= 0; i--) result[i] = heap.poll();
    return result;
}

private int dist(int[] p) {
    return p[0] * p[0] + p[1] * p[1];
}

Python

import heapq


def k_closest(points, k):
    heap = []  # (-distance, index): the farthest kept is on top
    for i, (x, y) in enumerate(points):
        heapq.heappush(heap, (-(x * x + y * y), i))
        if len(heap) > k:
            heapq.heappop(heap)
    result = []
    while heap:
        result.append(points[heapq.heappop(heap)[1]])
    return result[::-1]

C++

#include <bits/stdc++.h>
using namespace std;
class Solution {
  public:
    vector<vector<int>> kClosest(vector<vector<int>> &points, int k) {
        // Farthest first; for equal distances the earlier point leaves first.
        priority_queue<pair<int, int>> heap;
        for (int i = 0; i < int(points.size()); ++i) {
            heap.push({dist(points[i]), -i});
            if (int(heap.size()) > k)
                heap.pop();
        }
        vector<vector<int>> result(k);
        for (int i = k - 1; i >= 0; --i) {
            result[i] = points[-heap.top().second];
            heap.pop();
        }
        return result;
    }
    int dist(const vector<int> &p) {
        return p[0] * p[0] + p[1] * p[1];
    }
};

More Heaps & Priority Queues problems