← Questions
K closest points to the origin
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's technical phone screen, last asked Oct 2025. It tests heaps, quickselect and geometry.
Given points in the plane and an integer k, return the k points closest to the origin.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
k_closest(points: list[list[int]], k: int) -> list[list[int]]— theknearest points by Euclidean distance, in any order.
Example
k_closest([[1, 3], [-2, 2]], 1) -> [[-2, 2]] # 8 < 10
k_closest([[3, 3], [5, -1], [-2, 4]], 2) -> [[3, 3], [-2, 4]] # 18 and 20 beat 26
Constraints
-
1 <= k <= len(points) <= 10^5. Coordinates fit in 32-bit integers. - Ties in distance can go either way unless you agree on a rule.
Clarifying questions
- Must the output be sorted by distance?
- How should ties at the k-th distance be broken?
- Is
ksmall compared withn? Do the points arrive as a stream?
What a strong answer covers
- Comparing squared distances
x² + y², which avoids square roots and floating point. - Three approaches and their costs: sort everything (O(n log n)), a max-heap of size
k(O(n log k), works on a stream), quickselect (O(n) average, O(n²) worst case, changes the input order). - Which one to pick when
kis tiny, whenkis close ton, and when the data does not fit in memory. - Overflow of
x² + y²in fixed-width languages.
Follow-ups
- Points arrive one by one. Keep the current
kclosest. - Find the
kclosest points to a query point among many queries (a k-d tree or a grid index). - The points are spread across many machines.
Where it's asked
- Meta · Technical phone screen · Last asked Oct 202545 min · Two coding problems in CoderPad, about 20 minutes each · Usually no AI; some newer screens are AI-assisted
What it tests
heaps · quickselect · geometry
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
