The K Closest Points to Origin interview question asks you to find the k points in a 2D plane that are closest to the origin (0,0). Distance is measured using the standard Euclidean formula: x2+y2. Since we are only comparing distances, you can simplify the math by using squared distance x2+y2.
2. Why is this asked in interviews?
This is a standard question at companies like Meta, Amazon, and Salesforce. it tests your knowledge of Sorting and Heaps. For large datasets where k is small, interviewers look for the O(NlogK) heap approach or the O(N)Quickselect algorithm. it evaluations your ability to optimize for specific k values.
3. Algorithmic pattern used
There are three main patterns for this problem:
Sorting (O(NlogN)): Sort all points by distance and return the first k. Simple but not optimal for small k.
Max-Heap (O(NlogK)): Maintain a Max-Heap of size k. If a new point is closer than the heap's top (the furthest of the current k best), replace the top.
Quickselect (O(N) average): Use the quicksort partitioning logic to find the kth smallest distance and return all points to its left.
4. Example explanation
Points: [[1, 3], [-2, 2]], k=1
Distances squared:
(1,3)o12+32=10.
(−2,2)o(−2)2+22=8.
The point (−2,2) is closer.
Result: [[-2, 2]].
5. Common mistakes candidates make
Slow Math: Calculating the square root unnecessarily. d12<d22 implies d1<d2.
Heap Choice: Using a Min-Heap to store all N elements (O(NlogN)) instead of a Max-Heap of size k (O(NlogK)).
Tie-breaking: Not being consistent with points that have the same distance (though most problems don't require specific tie-breaking).
6. Interview preparation tip
Master Quickselect. It is the most impressive answer for any "Top K" or "Kth smallest" problem because it provides linear time complexity. Be ready to explain why the average time is O(N) but the worst case is O(N2). This is a core Quickselect interview pattern.