K Closest Points to Origin (LeetCode 973): Solution and Explanation
You are given a list of points on a plane and a number k. Return the k points that lie nearest to the origin by straight-line distance, in any order.
Watch it run step by step
Try your own input and write the code →Intuition
The simplest correct solution computes each point's distance, sorts all the points by it, and returns the first k. That is O(n log n), which is fine, but it does more work than the question asks for. You only care about which k points are closest, not the exact order of the other n - k.
A first useful observation: you never need the square root. Distance and squared distance rank points in exactly the same order, so comparing x * x + y * y is enough, and it keeps everything in integers.
The second observation is about what to remember while scanning. If you keep the k closest points seen so far, the only one that matters when a new point arrives is the farthest of them, since that is the one the newcomer might replace. A max heap keyed on distance gives you that farthest point at the top. Python's heapq is a min heap, so the code pushes the negated distance to get max heap behavior.
So the algorithm pushes every point and, whenever the heap grows past k, pops the top, which is the farthest point in it. After the scan the heap holds exactly the k nearest points. Each heap operation costs O(log k) rather than O(log n), which is a real win when k is much smaller than n.
Approach: Max heap of size k
- Create an empty list
heap. - For each point
(x, y), compute the squared distancedist = x * x + y * y. - Push
(-dist, [x, y])so the farthest point has the smallest key and sits at the top of the min heap. - If the heap now holds more than
kitems, pop once to discard the farthest point. - After all points are processed, return the points stored in the heap.
Step-by-step example
points = [[3,3],[5,-1],[-2,4]], k = 2
- The squared distances are 18 for [3,3], 26 for [5,-1] and 20 for [-2,4].
- Push (-18, [3,3]). The heap size is 1, which does not exceed 2.
- Push (-26, [5,-1]). The size is 2, still fine.
- Push (-20, [-2,4]). The size is 3, so pop the smallest key, -26, which removes [5,-1], the farthest point.
- The heap holds [3,3] and [-2,4], so the answer is [[3,3],[-2,4]].
Code: Python, Java, C++
1class Solution:
2 def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
3 # Use max heap of size k (negate distance for max heap behavior)
4 heap = []
5
6 for x, y in points:
7 dist = x * x + y * y
8 heapq.heappush(heap, (-dist, [x, y]))
9 if len(heap) > k:
10 heapq.heappop(heap)
11
12 return [point for _, point in heap]1class Solution {
2 public int[][] kClosest(int[][] points, int k) {
3 // Max heap based on distance
4 PriorityQueue<int[]> heap = new PriorityQueue<>(
5 (a, b) -> (b[0]*b[0] + b[1]*b[1]) - (a[0]*a[0] + a[1]*a[1])
6 );
7
8 for (int[] p : points) {
9 heap.add(p);
10 if (heap.size() > k) {
11 heap.poll();
12 }
13 }
14
15 return heap.toArray(new int[k][]);
16 }
17}1class Solution {
2public:
3 vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
4 auto cmp = [](const vector<int>& a, const vector<int>& b) {
5 return a[0]*a[0] + a[1]*a[1] < b[0]*b[0] + b[1]*b[1];
6 };
7 priority_queue<vector<int>, vector<vector<int>>, decltype(cmp)> heap(cmp);
8
9 for (auto& p : points) {
10 heap.push(p);
11 if (heap.size() > k) {
12 heap.pop();
13 }
14 }
15
16 vector<vector<int>> result;
17 while (!heap.empty()) {
18 result.push_back(heap.top());
19 heap.pop();
20 }
21 return result;
22 }
23};Time and space complexity
O(n log k)
Each of the n points causes one push and at most one pop on a heap that never holds more than k + 1 items, so each operation is O(log k).
O(k)
The heap never grows beyond k + 1 entries, and the output holds k points.
Other approaches
Sort by distance (time O(n log n), space O(n))
Sort all points by x * x + y * y and return the first k. It is the shortest code and perfectly acceptable when n is small or k is close to n.
Quickselect (time O(n) average, space O(1))
Partition the points around a pivot distance, as in quicksort, but only recurse into the side that contains the k-th position. The first k points afterward are the answer. It is linear on average but quadratic in the worst case unless the pivot is random.
Common mistakes
- Using a min heap of all points without negation and popping
ktimes. It works but costs O(n + k log n) and uses O(n) space, which defeats the purpose of a bounded heap. - Pushing positive distances into a size-k
heapq. Then the pop removes the closest point instead of the farthest one, and you end up with the k farthest points. - Computing
math.sqrtfor every point. It is unnecessary for comparison and introduces floating point values for no benefit. - Returning the heap tuples directly instead of extracting the point from each one.
Frequently asked questions
Why use a max heap for the k closest points?
You want to keep the k smallest distances, so the item you need to evict is the largest one among them. A max heap keeps that largest distance on top, ready to be removed in O(log k).
Do I need the square root to compare distances?
No. The square root preserves order, so comparing squared distances ranks the points identically. Skipping it avoids floating point math.
Is quickselect faster than a heap for K Closest Points?
On average quickselect runs in O(n), which beats O(n log k), and it uses no extra memory. The heap is more predictable, has no quadratic worst case, and also works on a stream of points.
What happens when two points are the same distance from the origin?
Either may be returned, since the problem accepts any valid set of k points in any order. In the Python code, ties on distance fall back to comparing the coordinate lists, which is harmless and just picks one of them deterministically.