Home
DSA Patterns
Heap / Priority Queue
K Closest Points to Origin
K Closest Points to Origin (LeetCode 973)
K Closest Points to Origin (LeetCode 973): find the K closest points to the origin (0, 0).
Problem Understanding
Each points[i] = [xi, yi] is a point on a flat X-Y plane. Return the k of them that lie nearest to the origin (0, 0).
"Nearest" means straight-line (Euclidean) distance, which for a point measured from the origin is √(x² + y²). The k points can come back in any order.
Algorithm Strategy
We want the K smallest distances.
- We can use a Max-Heap of size K.
- Why Max-Heap? Because we want to keep the "smallest" K elements. If the heap gets too big (> K), we want to evict the largest element (the one furthest away) to make room for smaller ones.
Algorithm:
- Initialize a Max-Heap.
- Iterate through all points.
- Calculate squared distance for each point (
x^2 + y^2). We don't need sqrt since it preserves order. - Push (distance, point) to heap.
- If size > k, pop the max element.
- Return the points remaining in the heap.
Interactive Visualization
k = 2 · NODES SHOW x² + y²
EMPTY HEAP
points
empty heap
Kept
0/2
Farthest kept
:
Returned
:
An empty max-heap keyed by distance: the farthest point kept is always on top. It keeps at most k = 2
Next
Read point 0: (3, 3)
Points
k
The plane shows every point. Once the heap holds k, a dashed circle passes through the farthest point kept: a new point has to land inside it to stay. The max-heap beside it is keyed by squared distance.
Dry Run
Points: [[3,3], [5,-1], [-2,4], [1,1], [0,-2]], k = 2
| Step | Point | x² + y² | Heap after push (root first) | Size > k? | Heap after |
|---|---|---|---|---|---|
| 1 | [3,3] |
18 | [18] |
No | [18] |
| 2 | [5,-1] |
26 | [26, 18] |
No | [26, 18] |
| 3 | [-2,4] |
20 | [26, 18, 20] |
Pop 26 | [20, 18] |
| 4 | [1,1] |
2 | [20, 18, 2] |
Pop 20 | [18, 2] |
| 5 | [0,-2] |
4 | [18, 2, 4] |
Pop 18 | [4, 2] |
Result: [[0,-2], [1,1]]: distances 4 and 2, in any order.
Edge Cases
- k = n: nothing is popped, and every point is returned.
- A point on the origin: its distance is 0, so it is never the farthest while other points are kept.
- Equal distances: LeetCode guarantees the answer is unique, so a tie never decides which points are returned.
- No square roots: comparing
x² + y²gives the same order as the true distance and stays in integers.
Solution
A max-heap of size k keyed by squared distance, in every language. JavaScript, TypeScript and C carry a small heap of their own.
K Closest Points to Origin Code
1class Heap {2 constructor(before) {3 this.items = [];4 this.before = before;5 }67 size() {8 return this.items.length;9 }1011 peek() {12 return this.items[0];13 }1415 push(item) {16 const a = this.items;17 a.push(item);18 let i = a.length - 1;19 while (i > 0 && this.before(a[i], a[(i - 1) >> 1])) {20 const parent = (i - 1) >> 1;21 [a[i], a[parent]] = [a[parent], a[i]];22 i = parent;23 }24 }2526 pop() {27 const a = this.items;28 const top = a[0];29 const last = a.pop();30 if (a.length > 0) {31 a[0] = last;32 let i = 0;33 while (true) {34 const left = 2 * i + 1, right = 2 * i + 2;35 let first = i;36 if (left < a.length && this.before(a[left], a[first])) first = left;37 if (right < a.length && this.before(a[right], a[first])) first = right;38 if (first === i) break;39 [a[i], a[first]] = [a[first], a[i]];40 i = first;41 }42 }43 return top;44 }45}4647var kClosest = function(points, k) {48 const heap = new Heap((a, b) => a[2] > b[2]);49 for (const [x, y] of points) {50 const dist = x * x + y * y;51 heap.push([x, y, dist]);52 if (heap.size() > k) {53 heap.pop();54 }55 }56 return heap.items.map(([x, y]) => [x, y]);57};
K Closest Points to Origin in Python, Java, C++, TypeScript and C
K Closest Points to Origin in Python
import heapq
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
heap = []
for x, y in points:
dist = x * x + y * y
heapq.heappush(heap, (-dist, x, y))
if len(heap) > k:
heapq.heappop(heap)
return [[x, y] for _, x, y in heap]K Closest Points to Origin in Java
class Solution {
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> b[2] - a[2]);
for (int[] p : points) {
int dist = p[0] * p[0] + p[1] * p[1];
heap.add(new int[] {p[0], p[1], dist});
if (heap.size() > k) {
heap.poll();
}
}
int[][] result = new int[heap.size()][];
int i = 0;
for (int[] entry : heap) result[i++] = new int[] {entry[0], entry[1]};
return result;
}
}K Closest Points to Origin in C++
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
priority_queue<array<int, 3>> heap;
for (auto& p : points) {
int dist = p[0] * p[0] + p[1] * p[1];
heap.push({dist, p[0], p[1]});
if (heap.size() > k) {
heap.pop();
}
}
vector<vector<int>> result;
while (!heap.empty()) {
result.push_back({heap.top()[1], heap.top()[2]});
heap.pop();
}
return result;
}
};K Closest Points to Origin in TypeScript
class Heap<T> {
items: T[] = [];
constructor(private before: (a: T, b: T) => boolean) {}
size(): number {
return this.items.length;
}
peek(): T {
return this.items[0];
}
push(item: T): void {
const a = this.items;
a.push(item);
let i = a.length - 1;
while (i > 0 && this.before(a[i], a[(i - 1) >> 1])) {
const parent = (i - 1) >> 1;
[a[i], a[parent]] = [a[parent], a[i]];
i = parent;
}
}
pop(): T {
const a = this.items;
const top = a[0];
const last = a.pop()!;
if (a.length > 0) {
a[0] = last;
let i = 0;
while (true) {
const left = 2 * i + 1, right = 2 * i + 2;
let first = i;
if (left < a.length && this.before(a[left], a[first])) first = left;
if (right < a.length && this.before(a[right], a[first])) first = right;
if (first === i) break;
[a[i], a[first]] = [a[first], a[i]];
i = first;
}
}
return top;
}
}
function kClosest(points: number[][], k: number): number[][] {
const heap = new Heap<number[]>((a, b) => a[2] > b[2]);
for (const [x, y] of points) {
const dist = x * x + y * y;
heap.push([x, y, dist]);
if (heap.size() > k) {
heap.pop();
}
}
return heap.items.map(([x, y]) => [x, y]);
}K Closest Points to Origin in C
typedef struct { int x, y, d; } Entry;
static void push(Entry* heap, int* size, Entry e) {
int i = (*size)++;
heap[i] = e;
while (i > 0 && heap[(i - 1) / 2].d < heap[i].d) {
int parent = (i - 1) / 2;
Entry t = heap[i]; heap[i] = heap[parent]; heap[parent] = t;
i = parent;
}
}
static void pop(Entry* heap, int* size) {
heap[0] = heap[--(*size)];
int i = 0;
while (1) {
int left = 2 * i + 1, right = 2 * i + 2, largest = i;
if (left < *size && heap[left].d > heap[largest].d) largest = left;
if (right < *size && heap[right].d > heap[largest].d) largest = right;
if (largest == i) break;
Entry t = heap[i]; heap[i] = heap[largest]; heap[largest] = t;
i = largest;
}
}
int** kClosest(int** points, int pointsSize, int* pointsColSize, int k, int* returnSize, int** returnColumnSizes) {
Entry* heap = malloc((k + 1) * sizeof(Entry));
int size = 0;
for (int i = 0; i < pointsSize; i++) {
int dist = points[i][0] * points[i][0] + points[i][1] * points[i][1];
push(heap, &size, (Entry) {points[i][0], points[i][1], dist});
if (size > k) {
pop(heap, &size);
}
}
int** result = malloc(size * sizeof(int*));
*returnColumnSizes = malloc(size * sizeof(int));
for (int j = 0; j < size; j++) {
result[j] = malloc(2 * sizeof(int));
result[j][0] = heap[j].x;
result[j][1] = heap[j].y;
(*returnColumnSizes)[j] = 2;
}
*returnSize = size;
free(heap);
return result;
}More practice: DSA interview questions with answers · patterns cheat sheet
