Browse curriculum

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:

  1. Initialize a Max-Heap.
  2. Iterate through all points.
  3. Calculate squared distance for each point ( x^2 + y^2 ). We don't need sqrt since it preserves order.
  4. Push (distance, point) to heap.
  5. If size > k, pop the max element.
  6. Return the points remaining in the heap.

Interactive Visualization

k = 2 · NODES SHOW x² + y²

EMPTY HEAP

points

(3, 3)
(5, -1)
(-2, 4)
(1, 1)
(0, -2)

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)

Free preview: the first 8 of 24 steps

Points

k

2

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 }
6
7 size() {
8 return this.items.length;
9 }
10
11 peek() {
12 return this.items[0];
13 }
14
15 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 }
25
26 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}
46
47var 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

The approach, step by step

  1. Measure

    For each point compute its squared distance x² + y².

  2. Push

    Push the point onto a max-heap keyed by that distance.

  3. Evict the farthest

    If the heap holds more than k points, pop its root; return the points left.

Frequently asked questions

Why a max-heap for the k closest points?

The heap holds the k nearest points so far with the farthest on top. A nearer point pushes it out; after every point has been read, the k left are the answer.


Why compare x² + y² instead of the distance?

Squaring preserves the order of non-negative distances, so the square root changes nothing about which points are closer, and skipping it keeps the arithmetic exact in integers.


What is the complexity?

O(n log k) time for n points and O(k) space for the heap. Sorting every point by distance would be O(n log n).

New to the technique behind this problem? Watch it run step by step:

Heaps Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description