Command Palette
Search for a command to run...
Problem 18.2 · Heaps and Priority QueuesMedium
What it teaches: K smallest by a computed key: a max-heap of size K keyed on squared distance.
Practise it on judges as “K Closest Points to Origin”.
The problem
Return the k points closest to (0, 0) by Euclidean distance, in any order.
Example 1
Input: points = [[1, 3], [-2, 2]], k = 1
Output: [[-2, 2]]
Squared distances 10 and 8.
Constraints
- 1 ≤ k ≤ n ≤ 10⁴
- −10⁴ ≤ x, y ≤ 10⁴
Pattern clues in the wording
These clues point to Top K with a Heap: Keep a heap of size k: a min-heap for the k largest, a max-heap for the k smallest.
Stuck? Take one hint at a time
Solution.java · starterimport java.util.*;
class Solution {
public int[][] kClosest(int[][] points, int k) {
return new int[0][];
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Test cases
| # | Input | Expected |
|---|
| 1 | points = [[1,3],[-2,2]] k = 1 | [[-2,2]] |
| 2 | points = [[3,3],[5,-1],[-2,4]] k = 2 | [[3,3],[-2,4]] |
+ 1 hidden test the code runner will check