Find K-th Smallest Pair Distance - Problem
Find K-th Smallest Pair Distance

Imagine you have an array of integers and need to find the k-th smallest distance between any two elements. The distance between two integers a and b is defined as the absolute difference |a - b|.

Given an integer array nums and an integer k, your task is to return the k-th smallest distance among all possible pairs nums[i] and nums[j] where 0 <= i < j < nums.length.

Example: If nums = [1, 3, 1] and k = 1, the pairs are (1,3), (1,1), and (3,1) with distances [2, 0, 2]. The 1st smallest distance is 0.

Input & Output

example_1.py — Basic case
$ Input: nums = [1,3,1], k = 1
› Output: 0
šŸ’” Note: The pairs are (1,3), (1,1), and (3,1) with distances [2, 0, 2]. The 1st smallest distance is 0.
example_2.py — Multiple same distances
$ Input: nums = [1,1,1], k = 2
› Output: 0
šŸ’” Note: All pairs have distance 0: (1,1), (1,1), (1,1). The 2nd smallest distance is still 0.
example_3.py — Larger array
$ Input: nums = [1,6,1], k = 3
› Output: 5
šŸ’” Note: The pairs are (1,6), (1,1), (6,1) with distances [5, 0, 5]. The 3rd smallest distance is 5.

Constraints

  • n == nums.length
  • 2 ≤ n ≤ 104
  • 0 ≤ nums[i] ≤ 106
  • 1 ≤ k ≤ n*(n-1)/2
  • All pairs (i,j) must satisfy i < j

Visualization

Tap to expand
šŸŽÆ Tournament Compatibility ScoringSorted Contestants by Skill Level113Binary Search: "How many pairs have compatibility ≤ X?"Search Range: [0, 2] → Find exact k-th scoreSliding Window CounterEfficiently count pairs ≤ targetResultK-th smallest distance found!Time: O(n log n + n log(max-min)) | Space: O(1)Much faster than generating all n² pairs!
Understanding the Visualization
1
Sort Contestants
Line up contestants by their skill level to enable efficient comparisons
2
Smart Estimation
Instead of calculating all scores, estimate 'how many pairs score better than X'
3
Binary Search
Use binary search to find the exact k-th best score
4
Sliding Window Count
For each candidate score, use sliding window to count qualifying pairs efficiently
Key Takeaway
šŸŽÆ Key Insight: Instead of generating all pair distances, we can binary search on the answer and count pairs efficiently using a sliding window on the sorted array.
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 24
42.0K Views
Medium Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
šŸ’” Explanation
AI Ready
šŸ’” Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen