☰ All problems

49. K Closest Points to Origin

MediumArrayHeapMathSorting

You are given an array points where points[i] = [x, y] is a point on the plane, and an integer k. Return the k points that are closest to the origin (0, 0), measured by ordinary (Euclidean) distance sqrt(x² + y²).

You may return the points in any order. The test data guarantees the answer is unique: the k-th closest point is strictly closer than the (k+1)-th, so there is never a tie at the cut-off. The same coordinates can appear more than once; each copy is a separate point.

Example 1
Input: points = [[3,4],[1,-1],[-2,2]], k = 1
Output: [[1,-1]]

Explanation: The squared distances are 25, 2 and 8, so [1,-1] is the closest.

Example 2
Input: points = [[5,0],[-1,-1],[2,2],[0,-3]], k = 2
Output: [[-1,-1],[2,2]]

Explanation: Squared distances 25, 2, 8, 9: the two smallest are 2 and 8. [[2,2],[-1,-1]] would also be accepted.

Example 3
Input: points = [[0,0]], k = 1
Output: [[0,0]]

Constraints

  • 1 <= k <= points.length <= 10^4
  • -10^4 <= x, y <= 10^4
  • The answer is unique (no tie at the k-th distance)

Follow-up: If the points arrive as an endless stream and you must always be able to report the current k closest, which of the approaches still works?

💡 Hint 1

You never need the actual square root: comparing x² + y² orders the points the same way.

💡 Hint 2

Sorting all points by distance works in O(n log n). To do better, keep only the best k seen so far in a max-heap keyed by distance, evicting the farthest when it grows past k.

💡 Hint 3

Quickselect on the distances finds the cut-off in O(n) on average, if you want to avoid the heap altogether.

/**
 * @param {number[][]} points
 * @param {number} k
 * @return {number[][]}
 */
function kClosest(points, k) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc