BugForge
DSA

K Closest Delivery Hubs

Mediumheapsorting 00:00

Hubs are points [x, y]. Return the indices of the k hubs closest to the origin, closest first; ties broken by smaller index.

Signature

kClosest(points: int[][], k: int) → int[]
Example 1
points = [[1,3],[-2,2],[2,-2]]
k = 2
output = [1,2]
dist² = 10, 8, 8 → indices 1, 2
Example 2
points = [[3,3],[5,-1],[-2,4]]
k = 1
output = [0]

Constraints

  • 1 ≤ k ≤ n ≤ 10^5
  • -10^4 ≤ x, y ≤ 10^4
Run checks the examples. Submit runs every hidden test (17, including large inputs that catch slow solutions).