Funcia
Lv.2geometryheapsorting

K Closest Points

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

You stand at the origin (0,0)(0, 0) of a map with NN convenience stores around you; store i is at points[i] = [x, y].

Return the indices of the k stores closest to the origin by Euclidean distance x2+y2\sqrt{x^2 + y^2}, ordered from closest to farthest. Ties are broken by the smaller index first.

Examples

pointskresult
[[3, 3], [1, -2], [-2, 2], [0, 1]]2[3, 1]
[[2, 0], [0, -2], [-1, 1], [5, 5]]3[2, 0, 1]
[[7, -7]]1[0]

Example 1 — Squared distances are 18, 5, 8, 1, so the two closest are store 3 and store 1.

Example 2 — Squared distances are 4, 4, 2, 50: store 2 first, then the tied stores 0 and 1 by index.

Example 3 — There is only one store.

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(points: int[][], k: int) → int[]

Constraints

  • 1≤N=1 \le N = points.length ≤200,000\le 200{,}000, each points[i] has length 2
  • −104≤x,y≤104-10^4 \le x, y \le 10^4 (several stores may share a location)
  • 1≤1 \le k ≤N\le N

Expected complexity

Time
O(N log N)
Space
O(N)

Examples

pointskExpected
[[3,3],[1,-2],[-2,2],[0,1]]2[3,1]
[[2,0],[0,-2],[-1,1],[5,5]]3[2,0,1]
[[7,-7]]1[0]

Hint

Hint

Compare squared distances x2+y2x^2 + y^2 — no square roots, exact integer comparison. Sorting by (squared distance, index) and taking the first k is O(Nlog⁡N)O(N \log N) (a size-k max-heap gives O(Nlog⁡k)O(N \log k)). Picking "the closest remaining point" k times is O(Nk)O(Nk) and times out for large k.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)226 msestimated
C++ (GCC, gnu++23)226 msderived
Python 3.131000 msderived
Java 251978 msderived
Kotlin 2.4 (JVM)1452 msestimated
C# 14 (.NET 10)1452 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4011verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.