Problem Description
Given an integer array and an integer k, find the kth smallest distance among all pairs (nums[i], nums[j]) with i < j. The distance of a pair is defined as the absolute difference between the two numbers.
Key Insights
- Sorting the array simplifies the calculation since the absolute difference is monotonic when traversing sequentially.
- Instead of generating all pair distances, use binary search on the range of possible distances.
- A two-pointer technique can efficiently count the number of pairs with a distance less than or equal to a given middle value.
- The binary search converges on the kth smallest distance based on the count of valid pairs.
Space and Time Complexity
Time Complexity: O(n log(max - min) + n log n) where n is the number of elements. O(n log n) for sorting and O(n log(max - min)) for binary search across the distance range. Space Complexity: O(1) extra space (ignoring the space required for sorting).
Solution
The approach starts by sorting the input array to leverage the ordered property of the numbers. The possible pair distances range between 0 and (max(nums) - min(nums)). Use binary search over this range to find the smallest distance d such that there are at least k pairs with a distance less than or equal to d. A helper function uses a two-pointer method on the sorted array to count the number of pairs satisfying the condition. Adjust the binary search boundaries based on this count until convergence.