K-th Smallest Pair Distance
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
pos[i] is the position of house i on a straight road. Among all pairs of distinct houses, the distance of a pair
is the absolute difference of their positions. Return the k-th smallest pair distance (pairs with equal distance are
counted separately; several houses may share a position).
Examples
| pos | k | result |
|---|---|---|
[1, 3, 1] | 1 | 0 |
[1, 6, 1] | 3 | 5 |
[9, 2, 5, 14] | 4 | 7 |
Example 1 — Distances 2, 0, 2.
Example 2 — Distances 0, 5, 5.
Example 3 — Distances 3, 4, 5, 7, 9, 12.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(pos: int[], k: long) → int
Constraints
-
pos.length -
pos[i] -
k(may exceed a 32-bit integer)
Expected complexity
- Time
- O(N log N + N log V)
- Space
- O(1)
Examples
| pos | k | Expected |
|---|---|---|
[1,3,1] | 1 | 0 |
[1,6,1] | 3 | 5 |
[9,2,5,14] | 4 | 7 |
Hint
Hint
Do not enumerate the ~ pairs. Sort the positions and binary search the answer d: the number of pairs with
distance ≤ d is counted in with two pointers (for each r, advance l while pos[r] - pos[l] > d, then add r - l).
The smallest d whose count is ≥ k is the answer. Total .
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1020 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 12 | verdict only |
| performance | 60 | 4 | verdict only |