K Closest Points to Origin - Top K Elements Pattern
K Closest Points to Origin in Java using the Top K Elements pattern: problem statement, approach, template, complexity, and interview tips.
K Closest Points to Origin
Problem Statement
Return the k points closest to the origin (0, 0).
Pattern: Top K Elements
Use a heap of size k (or a selection algorithm) to keep only the best k items while scanning the input.
Use this pattern when the question asks for the k largest, smallest, most frequent or closest items, or merges several sorted sources.
Approach
- Pick a min-heap for the k largest or a max-heap for the k smallest.
- Offer each item and drop the worst one when the heap exceeds k.
- Read the answer from the heap at the end.
Pattern Template (Java)
PriorityQueue<Integer> heap = new PriorityQueue<>(); // min-heap
for (int x : nums) {
heap.offer(x);
if (heap.size() > k) {
heap.poll();
}
}
// heap.peek() is the kth largest
Adapt this template to the exact rules of K Closest Points to Origin: decide what state you track, what condition moves the loop forward, and what the final answer is.
Complexity
O(n log k) time and O(k) space.
Interview Tips
- Mention quickselect as an O(n) average alternative.
- Use a comparator for custom ordering such as distance or frequency.
- Start with a brute-force idea, state its complexity, then explain how the Top K Elements pattern improves it.
- Walk through a small example and at least one edge case (empty input, a single element, duplicates).
Related Problems
- Kth Largest Element in an Array
- Top K Frequent Elements
- Find K Pairs with Smallest Sums
- Merge K Sorted Lists
Continue Learning
Parent: DSA Interview Learning Path | Previous: Find K Pairs with Smallest Sums | Next: Merge K Sorted Lists
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.