Closest Charging Stations

Easy · Heaps & Top-K · about 20 min

An electric car is parked at (0, 0). Charging stations are given as points [x, y]. Return the k stations closest to the car, by straight-line distance.

Order the answer from closest to farthest. When two stations are the same distance away, the one with the smaller x comes first, and if x is also equal, the smaller y comes first.

  • 0 <= k <= len(points). Coordinates are whole numbers. Two stations may sit at the same point.
  • Comparing x * x + y * y gives the same order as the real distance, with no square roots.

Example: nearest_stations([[3, 3], [5, -1], [-2, 4]], 2) → [[3, 3], [-2, 4]]

Hints

  • Work with x*x + y*y instead of the real distance. The order is the same and there are no square roots.
  • Sort key for one station: its squared distance, then x, then y. Smaller keys are better.
  • A max-heap of size k on that key lets you drop the worst station each time the heap gets too big.

Learn the pattern first: the Heaps & Top-K lesson.

More Heaps & Top-K problems