☰ All problems

K Closest Points to Origin

MediumArrayHeapMathSorting

A ride-hailing app shows each rider the k nearest available drivers. Positions are measured on a grid centred on the rider, so the rider stands at (0, 0) and points[i] = [x, y] is the position of driver i. Distance is ordinary straight-line (Euclidean) distance, sqrt(x² + y²).

Return the k drivers closest to the rider, in any order. The tests make sure there is no tie at the cut-off: the k-th closest driver is always strictly closer than the next one. Two drivers can stand at the same coordinates; they are still separate points.

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

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

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

Explanation: The squared distances are 40, 10, 16, 8, so only [6,2] is left out. Any order of the three points is accepted.

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

Explanation: Two drivers wait at the same spot, and both of them are returned.

Constraints

  • k is between 1 and the number of drivers, which is at most 10^4.
  • Every coordinate is an integer from -10^4 to 10^4.
  • There is never a tie at the k-th smallest distance.

Follow-up: If drivers keep coming online one at a time and the app must always know the current k nearest, which of these 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