Drone Nearest Drop-Offs

MediumheapAlso known as K Closest Points to Origin

A delivery drone lives on a rooftop pad. The town is mapped on a grid in metres with the pad at (0, 0), so a drop-off at (30, -40) is 30 metres east and 40 metres south. The drone flies in straight lines.

On a windy afternoon the operator only allows short hops, so the drone will make just k deliveries today: the k drop-offs closest to the pad, as the crow flies. The rest wait for tomorrow.

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) is closer even though its coordinates add up to 6, more than 5. Adding up |x| + |y| 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 by it, and take the first k. This is correct and takes O(n log n).

That is perfectly usable for 10,000 points. The heap version is O(n log k), which matters when k is small and the list is huge, or when points stream in and you cannot hold them all. The more common bug is not speed but measuring distance as |x| + |y|, or as x + y, which goes wrong for 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