1,3
-2,2
5,8
0,1
[0][1][2][3]
dist² to origin
·
·
·
·
[0][1][2][3]
Brute force · sort by distance
▸1given points, k2compute dist² = x² + y² for each3sort points by dist²4return the first k
state
- k2
Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.
Try one problemGiven an array of points on the plane and a value k, return the k points closest to the origin, measured by Euclidean distance. The answer may be returned in any order.
▸1given points, k2compute dist² = x² + y² for each3sort points by dist²4return the first k
line 1Return the k = 2 points NEAREST the origin. "Nearest" = smallest x² + y² — we never need the actual square root, the squared distance orders points the same way.