K Closest Points to Origin — Coding Interview Walkthrough
You’re in a coding interview. The interviewer says: “Given a list of points on a 2D plane, return the k closest to the origin.” The obvious answer is sort by distance. But interviewers want the heap solution — O(n log k) instead of O(n log n) — and strong candidates mention Quickselect.
The Problem
Given an array of points where points[i] = [xi, yi], return the k closest to the origin (0, 0). Return the answer in any order.
Example
Input: points = [[3,3],[5,-1],[-2,4]], k = 2
Output: [[3,3],[-2,4]]
Already comfortable with the solution? Practice it in a mock interview →
What Interviewers Are Actually Testing
| Skill | What Interviewers Observe |
|---|---|
| Distance comparison | Do you skip sqrt and compare squared distances? |
| Heap vs. sort | Do you know when a max-heap of size k beats full sort? |
Python heapq | Do you know it’s a min-heap and how to simulate max-heap? |
Step 1: The Key Insight
You don’t need sorted order — just the k smallest. A max-heap of size k evicts the farthest candidate each time a closer point arrives.
---
Python Implementation
Max-heap of size k:
import heapq
def kClosest(points: list[list[int]], k: int) -> list[list[int]]:
max_heap = []
for x, y in points:
dist = x**2 + y**2
heapq.heappush(max_heap, (-dist, x, y))
if len(max_heap) > k:
heapq.heappop(max_heap)
return [[x, y] for _, x, y in max_heap]
Time & Space Complexity
| Approach | Time | Space |
|---|---|---|
| Sort | O(n log n) | O(1) |
| Max-heap of k | O(n log k) | O(k) |
| Quickselect | O(n) expected | O(1) |
Common Interview Mistakes
- Using
sqrt. Unnecessary — comparex² + y²directly. - Not knowing
heapqis min-heap. Negate the key for max-heap behavior. - Proposing Quickselect without O(n²) caveat. Mention randomized pivoting mitigates worst case.
What a Strong Candidate Sounds Like
“Sort by squared distance is O(n log n). When k ≪ n, a max-heap of size k drops to O(n log k). For each point I push onto the heap; if size exceeds k, I pop the farthest. Quickselect gives O(n) expected but I’d go with the heap unless asked to optimize further.”
Related Problems to Practice
- Merge K Sorted Lists — Heap-based merging.
- Kth Smallest Element in a BST — K-th order selection.
Practice This in a Mock Interview
Start a mock interview for K Closest Points to Origin on Intervu.
Further reading:
- How to Prepare for a Coding Interview in 2026, the complete roadmap
- Why LeetCode alone isn’t enough, and what to practice instead
- Practice any LeetCode problem as a live mock interview
- The Grind 75 Pathway, a structured study plan with AI practice links
- Browse all walkthroughs on GitHub