Problem Statement

Find K-th Smallest Pair Distance

The "distance" between two numbers a and b is just how far apart they are on the number line. You find it by subtracting and ignoring the sign, so the distance between 1 and 6 is 5, and the distance between 3 and 3 is 0. Now take an array of numbers. Make every possible pair (each pair uses two different positions). Each pair has a distance. If you lined up all those distances from smallest to largest, this problem asks for the k-th one in that line. Given an array nums and a number k, return the k-th smallest distance among all pairs nums[i] and nums[j] where 0 <= i < j < nums.length.

hardBinary SearchBinary SearchTime: O(n log n + n log W) · Space: O(1)

Signals to notice

find kth smallest distance among all pairsbinary search on distancecounting pairs ≤ threshold

Brute force first

Compute all n(n-1)/2 distances, sort, return kth. Generates all pairs even though we only need one. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Sort the array. Binary search on the distance value: for each candidate distance d, count how many pairs have distance ≤ d using two pointers. Find the smallest d with count ≥ k. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Trace it on nums=[1,6,1], k=3

sort -> [1,1,6]; lo=0, hi=nums[-1]-nums[0]=5
mid=2: two-ptr count pairs(dist<=2) -> (1,1)=0 only -> count=1; 1<k=3 -> lo=3
now lo=3, hi=5; mid=4: count pairs(dist<=4) -> still only (1,1) -> count=1; 1<3 -> lo=5
now lo=5, hi=5; loop condition lo<hi fails
return lo=5  (3rd smallest distance: distances are {0,5,5})

What must stay true

In a sorted array, counting pairs with distance ≤ d is using two pointers (for each right pointer, find the leftmost left pointer where right - left ≤ d). The count is monotonically non-decreasing in d. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Shape of the loop

sort(nums); lo = 0; hi = nums[-1] - nums[0]
while lo < hi:
    mid = (lo + hi) // 2
    count = pairs with distance <= mid   # two-pointer sweep
    if count >= k: hi = mid    # smallest valid d is at most mid
    else:         lo = mid + 1
return lo

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

The binary search is on the distance value (0 to max-min), NOT on array indices. Each candidate distance is validated by counting pairs ≤ that distance. The fix is usually to return to the meaning of each move, not just the steps themselves.

Binary Search Pattern