Drone Nearest Drop-Offs

MediumheapAlso known as K Closest Points to Origin

A delivery drone flies in straight lines from a rooftop pad at (0, 0) on a town grid in metres, so (30, -40) is 30 m east and 40 m south. On a windy afternoon it makes just k deliveries: the k drop-offs closest to the pad, as the crow flies.

Your task

Write nearestDropOffs(points, k). points is a list of [x, y] drop-off positions. Return the k points with the smallest straight-line distance to (0, 0), in any order.

The input is chosen so the answer is unique: the k-th closest point is strictly closer than every point left out. The same position can appear twice (two parcels for one building); each counts as its own drop-off.

nearestDropOffs(points: int[][], k: int) → int[][] Any order of the returned list is accepted.

Examples

Example 1
Input
points = [[30, -40], [10, 20], [-5, 0], [60, 0]]
k = 2
Output
[[10, 20], [-5, 0]]
Why

Distances: (30, -40) is 50 m, (10, 20) is about 22.4 m, (-5, 0) is 5 m, (60, 0) is 60 m. The two closest are (-5, 0) and (10, 20).

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

(3, 3) is about 4.24 m away and (0, 5) is 5 m, so (3, 3) wins even though |x| + |y| = 6 is more than 5. That sum measures the wrong distance. The answer is (-1, -1) and (3, 3).

Constraints

  • 1 ≤ k ≤ points.length ≤ 10,000
  • -10,000 ≤ x, y ≤ 10,000
  • The k chosen points are strictly closer than all other points.
Start with brute force

Compute every distance, sort all n points, and take the first k: which is correct, runs in O(n log n), and is fine for 10,000 points. The heap is O(n log k), which matters when k is small and the list huge, or when points stream in. The more common bug is measuring distance as |x| + |y|, or as x + y, which breaks on negative coordinates.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code