719. Find K-th Smallest Pair Distance
HardView on LeetCode
Time: O(n log n + n log W)
Space: O(1)
Problem Overview
Find K-th Smallest Pair Distance (Hard) asks you to solve a structured algorithmic task. This is a common Array / Two Pointers pattern in coding interviews. Binary search on the distance; count pairs with distance ≤ m
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Binary search on the distance; count pairs with distance ≤ m
using a two-pointer sliding window on the sorted array.
Related patterns: Array, Two Pointers, Binary Search
719.cs
C#
// Approach: Binary search on the distance; count pairs with distance ≤ m
// using a two-pointer sliding window on the sorted array.
// Time: O(n log n + n log W) Space: O(1)
public class Solution
{
public int SmallestDistancePair(int[] nums, int k)
{
Array.Sort(nums);
int l = 0;
int r = nums[nums.Length - 1] - nums[0];
while (l < r)
{
int m = (l + r) / 2;
if (numPairDistancesNoGreater(nums, m) >= k)
r = m;
else
l = m + 1;
}
return l;
}
private int numPairDistancesNoGreater(int[] nums, int m)
{
int count = 0;
int j = 1;
for (int i = 0; i < nums.Length; i++)
{
while (j < nums.Length && nums[j] <= nums[i] + m)
++j;
count += j - i - 1;
}
return count;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 19. Remove Nth Node From End of List(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)