Find the K Closest Points

Problem Given a list of points in the plane and a target (often the origin), return the k points closest to the target by Euclidean distance.

Input / Output

  • Input: array of points [[x, y], ...], integer k (and optionally the target point).
  • Output: the k closest points (any order).

Constraints

  • 1 ≤ k ≤ n ≤ 10^5.
  • Compare squared distances to avoid unnecessary sqrt.

Example

  • points = [[1,3],[-2,2]], k = 1 → [[-2,2]] (distances² 10 vs 8).
  • points = [[3,3],[5,-1],[-2,4]], k = 2 → [[3,3],[-2,4]].
added …
LeaderboardSalaryAccount