719. Find K-th Smallest Pair Distance
Difficulty: Hard
Topics: Array
, Two Pointers
, Binary Search
, Sorting
The distance of a pair of integers a
and b
is defined as the absolute difference between a
and b
.
Given an integer array nums
and an integer k
, return the kth
smallest distance among all the pairs nums[i]
and nums[j]
where 0 <= i < j < nums.length
.
Example 1:
- Input: nums = [1,3,1], k = 1
- Output: 0
- Explanation: Here are all the pairs:
(1,3) -> 2 (1,1) -> 0 (3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
Example 2:
- Input: nums = [1,1,1], k = 2
- Output: 0
Example 3:
- Input: nums = [1,6,1], k = 3
- Output: 5
Constraints:
n == nums.length
2 <= n <= 104
0 <= nums[i] <= 106
1 <= k <= n * (n - 1) / 2
Hint:
- Binary search for the answer. How can you check how many pairs have distance <= X?
Solution:
We can use a combination of binary search and two-pointer technique. Here’s a step-by-step approach to solving this problem:
Approach:
Sort the Array: First, sort the array
nums
. Sorting helps in efficiently calculating the number of pairs with a distance less than or equal to a given value.Binary Search on Distance: Use binary search to find the
k
-th smallest distance. The search space for the distances ranges from0
(the smallest possible distance) tomax(nums) - min(nums)
(the largest possible distance).Count Pairs with Distance ā¤ Mid: For each mid value in the binary search, count the number of pairs with a distance less than or equal to
mid
. This can be done efficiently using a two-pointer approach.Adjust Binary Search Range: Depending on the number of pairs with distance less than or equal to
mid
, adjust the binary search range. If the count is less thank
, increase the lower bound; otherwise, decrease the upper bound.
Let’s implement this solution in PHP: 719. Find K-th Smallest Pair Distance
Explanation:
countPairsWithDistanceLessThanOrEqualTo: This function counts how many pairs have a distance less than or equal to
mid
. It uses two pointers, whereright
is the current element, andleft
is adjusted until the difference betweennums[right]
andnums[left]
is less than or equal tomid
.smallestDistancePair: This function uses binary search to find the
k
-th smallest distance. Thelow
andhigh
values define the current search range for the distances. Themid
value is checked using thecountPairsWithDistanceLessThanOrEqualTo
function. Depending on the result, the search space is adjusted.
This algorithm efficiently finds the k
-th smallest pair distance with a time complexity of O(n log(max(nums) - min(nums)) + n log n)
.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks š. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
Discover more from Coursity
Subscribe to get the latest posts sent to your email.