easyHeap / Priority QueuePure DSA~14 min
K Closest Servers To Origin
Each edge server sits at an (x, y) coordinate. To route a request, pick the k servers nearest the origin datacentre by Euclidean distance.
Problem
Given an array points where points[i] = [xi, yi] and an integer k, return the k points closest to the origin (0, 0) by Euclidean distance. The answer may be in any order.
Input
An array points of length n (1 ≤ k ≤ n ≤ 10^4), coordinates in [−10^4, 10^4].
Output
A list of the k closest points.
Constraints
- Distance is Euclidean; comparing squared distance avoids sqrt
- Ties may be broken arbitrarily
- 1 ≤ k ≤ n
Examples
Example 1
Input
points = [[1,3],[-2,2]], k = 1
Output
[[-2,2]]
Squared distances 10 vs 8; [-2,2] is closer.
Example 2
Input
points = [[3,3],[5,-1],[-2,4]], k = 2
Output
[[3,3],[-2,4]]
Squared distances 18, 26, 20 → keep 18 and 20.