15% off all plans & roadmaps Use code
See plansK Closest Points to Origin
- LeetCode 973
- Medium
- Heap (Priority Queue) Patterns
- Top K Elements (Selection/Frequency)
Updated
TL;DR: Return the k points with the smallest distance to (0, 0). Compare squared distances and keep a max-heap of size k, so each point costs O(log k) and the heap holds only the best k seen so far.
Problem
You get an array points where points[i] = [xi, yi] is a point on the X-Y plane, and an integer k. Return the k points closest to the origin (0, 0).
Distance is the Euclidean distance, sqrt(x^2 + y^2) for a point measured from the origin. You may return the answer in any order. The answer is guaranteed to be unique, apart from its order.
Example 1
Input: points = [[1,3],[-2,2]], k = 1 Output: [[-2,2]] Explanation: The distance from (1, 3) to the origin is sqrt(10). The distance from (-2, 2) is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer. We want only k = 1 point, so the answer is [[-2,2]].
Example 2
Input: points = [[3,3],[5,-1],[-2,4]], k = 2 Output: [[3,3],[-2,4]] Explanation: The answer [[-2,4],[3,3]] would also be accepted.
Constraints
1 <= k <= points.length <= 10^4-10^4 <= xi, yi <= 10^4
Constraints that matter
points.lengthup to 10^4 means even an O(n^2) scan is only about 10^8 steps at worst, but O(n log n) or better is the target an interviewer expects.- Coordinates up to 10^4 in magnitude give a squared distance of at most 2 * 10^8. That fits in a 32-bit int, so there is no overflow and no need for floating point.
1 <= k <= points.lengthmeans there is always a valid answer and k is never zero, so the heap never needs an empty-case guard.- The answer is guaranteed unique up to order, so ties at the k-th boundary never occur and you do not need a tie-break rule.
- Any output order is accepted, which is why a heap, whose internal order is partial, is a legal way to build the result.
Hints
Hint 1
This is a top-k selection problem.
Hint 2
Pick the closest unused point, mark it used, and repeat k times.
Solution
Intuition
This is a top-k selection problem. You do not need the points fully sorted. You need to know which k of them have the smallest distance, and the order inside that group does not matter.
Picture a shelf that holds only k jars, with the heaviest jar always on top. When a new jar makes k+1, knock the heaviest one off, so the shelf is the heap and jar weight is squared distance.
First, drop the square root. The function sqrt is increasing on non-negative numbers, so xx + yy orders points exactly as the true distance does. Integer comparison is faster and has no rounding error.
Next, ask what you must remember while scanning. Only the best k points so far. A new point can replace only the farthest of those k, so you need fast access to the maximum of a small group, with fast removal and insertion. That is a max-heap capped at size k.
The heap root is the worst point among the current best k. If a new point beats it, the root leaves and the new point enters. If not, the new point cannot be in the answer, because k points already beat it. Every discarded point has at least k better points, so nothing in the final heap is ever wrongly dropped.
Worked example
Input: points = [[1, 3], [-2, 2]], k = 1 Output: [[-2, 2]] Explanation: The squared distances are 1*1 + 3*3 = 10 for [1, 3] and 4 + 4 = 8 for [-2, 2]. Only one point may be returned, and 8 is smaller than 10, so the answer is [[-2, 2]].
Approach 1: Brute force: scan for the minimum k times
Pick the closest unused point, mark it used, and repeat k times. Each pick is a full linear scan over all n points. This is the plain translation of "find the closest point, then the next closest, and so on".
It needs no clever structure and it is correct for every input. The cost is k full scans, which grows quickly as k approaches n.
Steps
- Create a
usedarray of n flags, all false, and an empty result list. - Repeat k times: set
bestto none. - Scan every point that is not used and compare its squared distance xx + yy with the current best.
- Keep the index of the smallest squared distance.
- Mark that index used and append its point to the result.
- After k rounds, return the result.
Dry run
Input: points = [[1,3],[-2,2]], k = 1. Squared distances are 10 and 8.
- Round 1: nothing is used. Scan index 0 (distance 10), best = 0. Scan index 1 (distance 8), 8 < 10, so best = 1.
- Mark index 1 used and append
[-2, 2]. - k rounds are done, so the result is
[[-2, 2]], which matches the expected output.
Complexity
| Time | O(n * k) |
|---|---|
| Space | O(n) |
Here n is the number of points. Each of the k rounds scans all n points once with O(1) work per point, so the total is n * k. In the worst case k equals n, which gives O(n^2), about 10^8 steps at n = 10^4. The used array holds n booleans, which is O(n) extra space besides the output.
PythonTested in our runner
from typing import List, Optional
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
n = len(points)
used = [False] * n
result = []
for _ in range(k):
best = -1
best_dist = 0
for i in range(n):
if used[i]:
continue
d = points[i][0] * points[i][0] + points[i][1] * points[i][1]
if best == -1 or d < best_dist:
best = i
best_dist = d
used[best] = True
result.append(points[best])
return result
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] kClosest(int[][] points, int k) {
int n = points.length;
boolean[] used = new boolean[n];
int[][] result = new int[k][];
for (int r = 0; r < k; r++) {
int best = -1;
int bestDist = 0;
for (int i = 0; i < n; i++) {
if (used[i]) continue;
int d = points[i][0] * points[i][0] + points[i][1] * points[i][1];
if (best == -1 || d < bestDist) {
best = i;
bestDist = d;
}
}
used[best] = true;
result[r] = points[best];
}
return result;
}
};
C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
int n = points.size();
vector<bool> used(n, false);
vector<vector<int>> result;
for (int r = 0; r < k; r++) {
int best = -1;
int bestDist = 0;
for (int i = 0; i < n; i++) {
if (used[i]) continue;
int d = points[i][0] * points[i][0] + points[i][1] * points[i][1];
if (best == -1 || d < bestDist) {
best = i;
bestDist = d;
}
}
used[best] = true;
result.push_back(points[best]);
}
return result;
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} points
* @param {number} k
* @return {number[][]}
*/
var kClosest = function(points, k) {
const n = points.length;
const used = new Array(n).fill(false);
const result = [];
for (let r = 0; r < k; r++) {
let best = -1;
let bestDist = 0;
for (let i = 0; i < n; i++) {
if (used[i]) continue;
const d = points[i][0] * points[i][0] + points[i][1] * points[i][1];
if (best === -1 || d < bestDist) {
best = i;
bestDist = d;
}
}
used[best] = true;
result.push(points[best]);
}
return result;
};
GoTested in our runner
func kClosest(points [][]int, k int) [][]int {
n := len(points)
used := make([]bool, n)
result := make([][]int, 0, k)
for r := 0; r < k; r++ {
best := -1
bestDist := 0
for i := 0; i < n; i++ {
if used[i] {
continue
}
d := points[i][0]*points[i][0] + points[i][1]*points[i][1]
if best == -1 || d < bestDist {
best = i
bestDist = d
}
}
used[best] = true
result = append(result, points[best])
}
return result
}
C#Tested in our runner
public class Solution {
public int[][] kClosest(int[][] points, int k) {
int n = points.Length;
bool[] used = new bool[n];
int[][] result = new int[k][];
for (int r = 0; r < k; r++) {
int best = -1;
int bestDist = 0;
for (int i = 0; i < n; i++) {
if (used[i]) continue;
int d = points[i][0] * points[i][0] + points[i][1] * points[i][1];
if (best == -1 || d < bestDist) {
best = i;
bestDist = d;
}
}
used[best] = true;
result[r] = points[best];
}
return result;
}
}
Approach 2: Sort by squared distance
What's slow: the brute force rescans all n points for every one of the k picks, so the same distances are compared again and again. When k is large, the work grows toward n^2.
The insight that fixes it: order all points once. A single sort by squared distance puts the k closest points in the first k slots, and a library sort needs only O(n log n) comparisons.
Steps
- Define the key of a point as xx + yy. Skip the square root.
- Sort the whole
pointsarray by this key in ascending order. - Take the first k points of the sorted array.
- Return them.
Dry run
Input: points = [[1,3],[-2,2]], k = 1.
- Keys: [1, 3] has key 10 and [-2, 2] has key 8.
- Sorted ascending:
[[-2, 2], [1, 3]]. - Take the first k = 1 entries:
[[-2, 2]], which matches the expected output.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(1) to O(n) |
Here n is the number of points. A comparison sort does O(n log n) comparisons, each in O(1) because the key is two multiplications and an add. The extra space depends on the language: in-place sorts such as Java's and Go's use little beyond the stack, while Python's sorted copies the list, which is O(n). The sort also touches points that are not in the answer, so it does more work than necessary when k is small.
PythonTested in our runner
from typing import List, Optional
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]
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] kClosest(int[][] points, int k) {
// Squared distance is at most 2 * 10^8, so int does not overflow
Arrays.sort(points, (a, b) ->
Integer.compare(a[0] * a[0] + a[1] * a[1], b[0] * b[0] + b[1] * b[1]));
return Arrays.copyOfRange(points, 0, k);
}
};
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
sort(points.begin(), points.end(), [](const vector<int>& a, const vector<int>& b) {
return a[0] * a[0] + a[1] * a[1] < b[0] * b[0] + b[1] * b[1];
});
return vector<vector<int>>(points.begin(), points.begin() + k);
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} points
* @param {number} k
* @return {number[][]}
*/
var kClosest = function(points, k) {
const sorted = [...points].sort((a, b) =>
(a[0] * a[0] + a[1] * a[1]) - (b[0] * b[0] + b[1] * b[1]));
return sorted.slice(0, k);
};
GoTested in our runner
import "sort"
func kClosest(points [][]int, k int) [][]int {
sort.Slice(points, func(i, j int) bool {
return points[i][0]*points[i][0]+points[i][1]*points[i][1] <
points[j][0]*points[j][0]+points[j][1]*points[j][1]
})
return points[:k]
}
C#Tested in our runner
public class Solution {
public int[][] kClosest(int[][] points, int k) {
Array.Sort(points, (a, b) =>
(a[0] * a[0] + a[1] * a[1]).CompareTo(b[0] * b[0] + b[1] * b[1]));
return points.Take(k).ToArray();
}
}

Solution pattern
Top K Elements (Selection/Frequency)
Part of Heap (Priority Queue) Patterns
Approach 3: Max-heap of size kOptimalTop K Elements (Selection/Frequency)
What's slow: sorting orders all n points, including the n - k that will never be returned. Sorting also needs the whole input in memory, and its cost does not shrink when k is small.
The insight that fixes it: keep only the best k points seen so far in a max-heap keyed by squared distance. The root is the farthest of the k.
For each new point, push it. If the heap now holds k + 1 points, pop the root. The popped point is the farthest of the k + 1, so it cannot be in the answer. Each push and pop costs O(log k) instead of a full sort.
Steps
- Create an empty max-heap ordered by squared distance, so the farthest point sits at the root.
- Walk through the points one at a time.
- Push the current point with its squared distance.
- If the heap size is now greater than k, pop the root, which removes the farthest point.
- After the last point, the heap holds exactly the k closest points.
- Copy the heap contents into the result in any order and return it.
Dry run
Input: points = [[1,3],[-2,2]], k = 1. Squared distances are 10 and 8. The heap stores (distance, point) with the largest distance at the root.
| Step | Point | Squared distance | Action | Heap after | Size vs k |
|---|---|---|---|---|---|
| 1 | [1, 3] | 10 | push | {(10, [1,3])} | 1 <= 1, keep |
| 2 | [-2, 2] | 8 | push | {(10, [1,3]), (8, [-2,2])} | 2 > 1, pop |
| 2b | pop root (10) | {(8, [-2,2])} | 1 |
After the last point the heap holds one entry, so the result is [[-2, 2]]. This matches the expected output.
Complexity
| Time | O(n log k) |
|---|---|
| Space | O(k) |
Here n is the number of points. The loop runs n times, and each iteration does one push and at most one pop on a heap that never holds more than k + 1 entries. Each heap operation costs O(log(k + 1)), so the total is O(n log k).
The heap stores at most k + 1 entries, so the extra space is O(k) besides the output. When k is close to n, this is no better than sorting, but it never loses by more than a constant factor.
PythonTested in our runner
import heapq
from typing import List, Optional
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
# heapq is a min-heap, so store the negated distance to get a max-heap.
# The index breaks ties so lists are never compared.
heap = []
for i, (x, y) in enumerate(points):
heapq.heappush(heap, (-(x * x + y * y), i))
if len(heap) > k:
heapq.heappop(heap) # removes the farthest point
return [points[i] for _, i in heap]
JavaTested in our runner
import java.util.*;
class Solution {
public int[][] kClosest(int[][] points, int k) {
// Max-heap on squared distance: the farthest point is at the root
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) ->
Integer.compare(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();
}
}
int[][] result = new int[k][];
for (int i = 0; i < k; i++) {
result[i] = heap.poll();
}
return result;
}
};
C++Tested in our runner
#include <vector>
#include <queue>
using namespace std;
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
// priority_queue is a max-heap by default: largest distance on top
priority_queue<pair<int, int>> heap;
for (int i = 0; i < (int)points.size(); i++) {
int d = points[i][0] * points[i][0] + points[i][1] * points[i][1];
heap.push({d, i});
if ((int)heap.size() > k) {
heap.pop();
}
}
vector<vector<int>> result;
while (!heap.empty()) {
result.push_back(points[heap.top().second]);
heap.pop();
}
return result;
}
};
JavaScriptTested in our runner
/**
* @param {number[][]} points
* @param {number} k
* @return {number[][]}
*/
var kClosest = function(points, k) {
// JavaScript has no built-in heap, so this is a small array-based max-heap.
// Each entry is [squaredDistance, index].
const heap = [];
const swap = (i, j) => {
const t = heap[i];
heap[i] = heap[j];
heap[j] = t;
};
const siftUp = (i) => {
while (i > 0) {
const p = (i - 1) >> 1;
if (heap[p][0] >= heap[i][0]) break;
swap(p, i);
i = p;
}
};
const siftDown = (i) => {
const n = heap.length;
while (true) {
const l = 2 * i + 1;
const r = l + 1;
let m = i;
if (l < n && heap[l][0] > heap[m][0]) m = l;
if (r < n && heap[r][0] > heap[m][0]) m = r;
if (m === i) break;
swap(m, i);
i = m;
}
};
for (let i = 0; i < points.length; i++) {
const d = points[i][0] * points[i][0] + points[i][1] * points[i][1];
heap.push([d, i]);
siftUp(heap.length - 1);
if (heap.length > k) {
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
siftDown(0);
}
}
}
return heap.map((e) => points[e[1]]);
};
GoTested in our runner
import "container/heap"
// maxHeap holds point indices, ordered so the farthest point is at the root.
type maxHeap struct {
idx []int
pts [][]int
}
func (h *maxHeap) dist(i int) int {
p := h.pts[h.idx[i]]
return p[0]*p[0] + p[1]*p[1]
}
func (h *maxHeap) Len() int { return len(h.idx) }
func (h *maxHeap) Less(i, j int) bool { return h.dist(i) > h.dist(j) }
func (h *maxHeap) Swap(i, j int) { h.idx[i], h.idx[j] = h.idx[j], h.idx[i] }
func (h *maxHeap) Push(x interface{}) { h.idx = append(h.idx, x.(int)) }
func (h *maxHeap) Pop() interface{} {
n := len(h.idx)
v := h.idx[n-1]
h.idx = h.idx[:n-1]
return v
}
func kClosest(points [][]int, k int) [][]int {
h := &maxHeap{pts: points}
for i := range points {
heap.Push(h, i)
if h.Len() > k {
heap.Pop(h)
}
}
result := make([][]int, 0, k)
for _, i := range h.idx {
result = append(result, points[i])
}
return result
}
C#Tested in our runner
public class Solution {
public int[][] kClosest(int[][] points, int k) {
// Ordered by (squared distance, index). Max is the farthest point.
// The index makes every entry unique, so no point is lost to a tie.
var set = new SortedSet<(int, int)>();
for (int i = 0; i < points.Length; i++) {
int d = points[i][0] * points[i][0] + points[i][1] * points[i][1];
set.Add((d, i));
if (set.Count > k) {
set.Remove(set.Max);
}
}
return set.Select(t => points[t.Item2]).ToArray();
}
}
Common mistakes
- Calling
Math.sqrtor** 0.5on every point. It adds cost and floating-point noise for no benefit. Comparex*x + y*ydirectly. - Using a min-heap of size k. Popping then removes the closest point, so you keep the k farthest. Store negated distances in Python, or reverse the comparator in Java, so the root is the largest distance.
- Pushing
(dist, [x, y])into a Python heap with no tie-breaker. Equal distances make Python compare the lists, which works but wastes time and hides intent. Push(-dist, index)instead. - Popping before pushing, or popping when
len(heap) == k. With the checklen(heap) > kafter the push, the heap always keeps the k best. Pop only when the size exceeds k. - Sorting by
a[0] - b[0]or byx + y. The key must bex*x + y*y. Using the sum of coordinates treats (3, -3) as distance 0, which is wrong. - Returning
points[:k]from the sort version without sorting first, or returningheapentries that still hold the distance. The result must contain only the[x, y]pairs.
Edge cases
points = [[0,0]],k = 1: a single point at the origin, so return[[0,0]].k == points.length: every point is returned. The heap never pops, and sorting returns the full array.- Negative coordinates such as
[-2, 2]and[2, -2]are at the same distance. Squaring removes the sign, and the uniqueness guarantee means such ties never straddle the k-th boundary. - Points with large coordinates, such as
[10000, 10000]: the squared distance is 2 * 10^8, which fits in a 32-bit int in Java, C++ and C#. - Duplicate points, for example
[[1,1],[1,1],[5,5]]withk = 2: both copies are kept, giving[[1,1],[1,1]]. Index tie-breakers keep both entries. k = 1on a large input: the heap holds one entry, so each step is O(1) work and the total is O(n).
Follow-ups interviewers ask
- Can you do better than O(n log k) on average?
- Yes. Use quickselect on squared distance. Pick a pivot, partition the array around it, and recurse into only the side that contains the k-th boundary. The expected time is O(n). The worst case is O(n^2) with bad pivots, which a random pivot makes very unlikely. It works in place, so extra space is O(1) besides recursion, but it reorders the input.
- What if the points arrive as a stream or do not fit in memory?
- Use the max-heap of size k. You process one point at a time and keep only k entries, so memory is O(k) regardless of how many points arrive. At any moment the heap holds the k closest points seen so far. Sorting and quickselect both need all points in memory, so they do not apply.
- What changes when k is very close to n?
- Think of it as removing the n - k farthest points instead. A min-heap of size n - k keyed by distance would hold the points to discard, or you can sort once. When k is near n, the log k factor is close to log n, so the heap has no advantage over a plain sort and the simpler sort is a fine choice.
K Closest Points to Origin FAQ
What is the time complexity of K Closest Points to Origin?
The max-heap solution runs in O(n log k) time and O(k) extra space, where n is the number of points. Sorting is O(n log n). Quickselect is O(n) on average. Repeatedly scanning for the minimum is O(n * k).
Why use a max-heap for K Closest Points to Origin?
You want to keep the smallest distances, so the item you must be able to evict quickly is the largest one. A max-heap exposes the largest distance at the root in O(1) and removes it in O(log k). A min-heap would expose the closest point, which is the one you want to keep.
Do I need to take the square root of the distance?
No. Square root is increasing for non-negative numbers, so squared distances sort the points in exactly the same order. Skipping it saves time and avoids floating-point rounding.
Can K Closest Points to Origin be solved in O(1) extra space?
Yes, with caveats. An in-place sort or quickselect uses O(1) extra space, apart from the stack, but it modifies the input array. The max-heap approach needs O(k) space, and keeping the input untouched while using O(1) space is not possible with these methods.
How do I write K Closest Points to Origin in Python with a heap?
Use heapq with negated squared distance: push (-(x*x + y*y), i) and pop when len(heap) > k. The heap then holds the k closest. In Java use a PriorityQueue with a comparator that puts the larger distance first.
Does the order of the returned points matter?
No. The problem accepts any order. A heap returns points in an arbitrary internal order, and the sort version returns them closest first. Both are accepted.
Asked at
See which companies ask this — Pro
Related problems
- Top K Frequent Elements · same technique: Top K Elements (Selection/Frequency)
- Kth Largest Element in an Array · same technique: Top K Elements (Selection/Frequency)
- Sort Characters By Frequency · same technique: Top K Elements (Selection/Frequency)
- Last Stone Weight · same technique: Top K Elements (Selection/Frequency)
- Kth Largest Element in a Stream · same technique: Top K Elements (Selection/Frequency)
- Merge k Sorted Lists · next harder, same pattern
- Meeting Rooms II · same pattern: Heap (Priority Queue) Patterns
- Design Twitter · same pattern: Heap (Priority Queue) Patterns
- Reorganize String · same pattern: Heap (Priority Queue) Patterns
- Single-Threaded CPU · same pattern: Heap (Priority Queue) Patterns