Example 1
- Input
- points = [[1,3],[-2,2]], k = 1
- Output
- [[-2,2]]
The squared distances are 10 and 8, so [-2,2] is closer and is the only point returned.
Given points on a plane and an integer k, return the k points nearest the origin using Euclidean distance. The answer may come back in any order.
Given points, where each entry [x,y] is an integer coordinate pair, and k, return the k points with smallest Euclidean distance to the origin [0,0]. Return them in any order.
Compare squared distances : square root increases with its input, so it cannot change which points are nearer. The statement guarantees a unique selected answer except for output order. These implementations also handle tied cutoff distances by returning any valid k-point selection. They preserve the input and return fresh coordinate arrays.
The squared distances are 10 and 8, so [-2,2] is closer and is the only point returned.
The squared distances are 18, 26 and 20, so [3,3] and [-2,4] are the two closest.
With k equal to n, every point must be returned. The origin has squared distance 0, and the other two points tie at 1. Both tied points are included, so the selected answer remains unique; their relative order is irrelevant.
The distances are 8, 8, 9, and 0. Each duplicate is a separate input occurrence, so both copies of [-2,-2] must be kept with the origin. Keeping only distinct coordinate pairs would wrongly return fewer than three points.
The closest points have the smallest squared distances: Example 1 compares 10 for [1,3] with 8 for [-2,2]. Sorting ranks every point. A bounded max-heap only tracks the current k winners; its root is the farthest retained candidate, exactly the one to discard when the candidate set becomes too large. Coordinate signs matter when locating a point, but disappear when measuring distance.
Reveal Sort by Distance: intuition, complexity, and code
x*x + y*y instead of the true Euclidean distance to stay in exact integer arithmetic.k winners are needed, so most of that ordering is wasted.k candidates in a max-heap and evict the top whenever a closer point arrives.For the k smallest of anything, cap a max-heap at k entries and let each arrival evict the current worst survivor.