The Find K-th Smallest Pair Distance interview question asks you to find the -th smallest value among all absolute differences for every possible pair of indices in an array. For an array of size , there are such distances.
This "Hard" problem is a favorite at Google and Microsoft because it tests your ability to use Binary Search on the Answer. Since you can't generate all distances, you must search for the distance value itself. It evaluations your mastery of combining binary search with the Two Pointers interview pattern to count pairs efficiently.
This problem uses Binary Search on Value Range and Sliding Window (Two Pointers).
[0, max(nums) - min(nums)].mid, count how many pairs have a distance .
right, find the smallest left such that nums[right] - nums[left] <= mid. All indices between left and right form valid pairs.mid could be the answer (try smaller). Otherwise, the answer must be larger.nums = [1, 3, 1],
[1, 1, 3]. Range: [0, 2].mid = 0: Pairs is 1 (index 0 and 1). Count = 1.When asked for the "-th" anything in a large combinatorial space, always check if you can solve the "Check(X): are there at least items smaller than X?" sub-problem efficiently. If you can, Binary Search on the Answer is the way to go.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum Time to Eat All Grains | Hard | Solve | |
| Number of Subsequences That Satisfy the Given Sum Condition | Medium | Solve | |
| Count the Number of Fair Pairs | Medium | Solve | |
| Successful Pairs of Spells and Potions | Medium | Solve | |
| Friends Of Appropriate Ages | Medium | Solve |