↻one more pass.
Heaps · Medium

K Closest Points to Origin: the idea to remember.

Return any k points with the smallest Euclidean distance to the origin.

Solve on LeetCode ↗

The core insight

Compare squared distances and retain only k points in a max heap.

Why it works

Whenever there are more than k candidates, removing the farthest leaves the k nearest among all points processed.

The mistake to avoid

The result order is arbitrary. Compare squared distances without unnecessary square roots.

Time: O(n log(k+1))Space: O(k)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

// Java reference adapted from neetcode-gh/leetcode (MIT).
// Compare squared distances and retain only k points in a max heap.
public int[][] kClosest(int[][] points, int k) {
    PriorityQueue<int[]> q = new PriorityQueue<>((a, b) ->
        Integer.compare(
            (b[0] * b[0] + b[1] * b[1]),
            (a[0] * a[0] + a[1] * a[1])
        )
    ); 
    for (int[] point : points) {
        q.add(point);

        if (q.size() > k) {
            q.remove();
        }
    }
    int[][] ans = new int[k][2];
    for (int i = 0; i < k; i++) {
        int[] cur = q.poll();
        ans[i][0] = cur[0];
        ans[i][1] = cur[1];
    }
    return ans;
}

Java reference adapted from neetcode-gh/leetcode · MIT license

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.