Nearest Charging Stations

heap · max-heap · geometry

Your electric car is parked at (0, 0) on a city map, and points lists the charging stations as [x, y] coordinates. Write k_closest(points, k) that returns the k stations nearest the car in straight-line (Euclidean) distance, as a list of [x, y] lists in any order. No two stations tie at the cut-off, so the answer is unique.

Examples

Input:  points = [[2, 4], [-3, 1]], k = 1
Output: [[-3, 1]]
Explanation: distance^2 of [2, 4] is 20, of [-3, 1] is 10.
Input:  points = [[4, -1], [1, 5], [-2, -2], [0, 3]], k = 2
Output: [[-2, -2], [0, 3]]

Constraints

  • 1 <= k <= len(points) <= 10**4
  • -10**4 <= x, y <= 10**4

Goals

  • Simulate a max-heap with heapq by negating the key
  • Compare distances without a square root
  • Keep the k best candidates in a bounded heap while scanning a list
Starting Python…