← Questions

K closest points to the origin

0
MetaCodingLast asked Oct 2025

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]] — the k nearest 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 k small compared with n? 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 k is tiny, when k is close to n, 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 k closest.
  • Find the k closest 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

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