hardBinary SearchBinary Search

Find K-th Smallest Pair Distance

hardTime: O(n log n + n log W)Space: O(1)

Recognize the pattern

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

Brute force idea

A straightforward first read of Find K-th Smallest Pair Distance is this: 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.

Better approach

A calmer way to see Find K-th Smallest Pair Distance is this: 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.

Key invariant

The truth you want to protect throughout Find K-th Smallest Pair Distance is this: 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.

Watch out for

One easy way to drift off course in Find K-th Smallest Pair Distance is this: 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