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
Given an integer array
Example: If
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
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.
š”
Explanation
AI Ready
š” Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code