The distance between two numbers is the absolute value of their difference. You are given a list nums and a number k.
Look at every pair of positions i < j and the distance between nums[i] and nums[j]. Sort all those distances from smallest to largest, repeats included, and return the k-th one (counting from 1).
Example 1
Input: nums = [3, 8, 1], k = 2 Output: 5 Why: the distances are 5, 2 and 7; sorted, the second is 5
2 more examples and the constraints
Example 2
Input: nums = [4, 4, 4, 4], k = 5 Output: 0 Why: all six pairs have distance 0
Example 3
Input: nums = [2, 9, 5, 7], k = 4 Output: 4 Why: sorted distances are 2, 2, 3, 4, 5, 7
Constraints
- 2 ≤ length of nums ≤ 10,000
- 0 ≤ nums[i] ≤ 1,000,000
- 1 ≤ k ≤ n(n − 1) / 2, the number of pairs
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- List every distanceO(n² log n)
- Binary search on the distanceO(n log W)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 numbers | Verdict |
|---|---|---|---|
| List every distance | O(n² log n) | Too slow and too much memory | |
| Binary search on the distance | O(n log n + n log W) | Best; never lists the pairs |
n = length of nums, W = largest value minus smallest (at most 1,000,000).
Edge cases to test
- All equal. [4, 4, 4, 4] gives 0 for every k; the search range is just 0..0.
- Two numbers. [0, 1000000] with k = 1 gives 1,000,000, the only pair.
- k is the last pair. k = n(n − 1) / 2 returns the largest distance, max − min.
- Repeated distances. [2, 9, 5, 7] has 2 twice; k = 1 and k = 2 both give 2.
Common mistakes
- Searching for a d where the count equals k exactly; with repeated distances it may never equal k.
- Counting pairs within d by checking all pairs again, which brings back O(n²) per round.
- Forgetting to sort before the sliding-window count.
How to talk through it
- 1Clarify. Are repeated distances counted separately? Is k 1-based? How large are the values?
- 2Give the brute force. List all n²/2 distances and sort: say why it fails at 10,000 numbers.
- 3Turn it into a yes/no question. Counting pairs within d is monotone in d, so binary search the answer.
- 4Code the count. Sort, then slide a window: for each j, add j − i once nums[j] − nums[i] ≤ d.
- 5Test out loud. Run all-equal numbers, k = 1 and k at the last pair before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?