K Closest Points
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
You stand at the origin of a map with 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 , ordered from closest to
farthest. Ties are broken by the smaller index first.
Examples
| points | k | result |
|---|---|---|
[[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
-
points.length, eachpoints[i]has length 2 - (several stores may share a location)
-
k
Expected complexity
- Time
- O(N log N)
- Space
- O(N)
Examples
| points | k | Expected |
|---|---|---|
[[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 — no square roots, exact integer comparison. Sorting by (squared distance, index) and
taking the first k is (a size-k max-heap gives ). Picking "the closest remaining point" k
times is and times out for large k.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 226 ms | estimated |
| C++ (GCC, gnu++23) | 226 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1978 ms | derived |
| Kotlin 2.4 (JVM) | 1452 ms | estimated |
| C# 14 (.NET 10) | 1452 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 11 | verdict only |
| performance | 60 | 4 | verdict only |