K Closest Points to Origin
LeetCode 973 · Medium · solution, intuition & step-by-step walkthrough
Max-heap of size k on squared distance.
This is how I solved K Closest Points to Origin (LeetCode 973), a medium problem from the Top K pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Keep only the k best candidates seen so far in a max-heap keyed by distance. A new point enters only if it's closer than the farthest point currently kept, which it then replaces.
Approach
- 1
Squared distance x² + y² (no square root needed).
- 2
Heap smaller than k → push.
- 3
Closer than the heap's farthest → pop it and push the new point.
- 4
The heap holds the answer.
How I solved it
Max-heap of size kPythonO(n log k) time · O(k) space
import heapq
class Solution:
def kClosest(self, points, k):
pq = [] # max-heap via negative distance
for point in points:
x, y = point
distance = x ** 2 + y ** 2
if len(pq) < k:
heapq.heappush(pq, (-distance, point))
elif distance < -pq[0][0]:
heapq.heappop(pq)
heapq.heappush(pq, (-distance, point))
return [item[1] for item in pq]K Closest Points to Origin — FAQ
What is the intuition behind K Closest Points to Origin?
Keep only the k best candidates seen so far in a max-heap keyed by distance. A new point enters only if it's closer than the farthest point currently kept, which it then replaces.
How do you solve K Closest Points to Origin (LeetCode 973)?
1. Squared distance x² + y² (no square root needed). 2. Heap smaller than k → push. 3. Closer than the heap's farthest → pop it and push the new point. 4. The heap holds the answer.
What is the time and space complexity of K Closest Points to Origin?
Time: O(n log k). Space: O(k). (Accepted approach: Max-heap of size k.)
What are common mistakes in K Closest Points to Origin?
Comparing squared distances avoids floating-point roots.