↓Skip to main content
  1. LeetCode/

LeetCode 719: Find K-th Smallest Pair Distance

·2 mins· ·
LeetCode Hard Binary-Search Two-Pointers Sliding-Window Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2026-09-06

  • Submissions: Accepted → Accepted (renamed variables)

Approach
#

There are n(n-1)/2 pairs, about 5 * 10^7 at n = 10^4, too many to list and sort.

Instead, binary search on the answer:

  • Distances lie in [0, max - min].
  • count(d) = the number of pairs with distance <= d; it grows with d, so it is monotonic.
  • The first d with count(d) >= k is the k-th smallest distance.

Computing count(d): sort, then slide a window. For each right end right, move the left end until nums[right] - nums[left] <= d; every index from left to right - 1 pairs with right at distance <= d, which is right - left pairs.

My Solution
#

class Solution:
    def smallestDistancePair(self, nums: List[int], k: int) -> int:
        nums.sort()
        n = len(nums)

        def count_within(d: int) -> int:
            count = left = 0
            for right in range(n):
                while nums[right] - nums[left] > d:
                    left += 1
                count += right - left
            return count

        lo, hi = 0, nums[-1] - nums[0]
        while lo < hi:
            mid = (lo + hi) // 2
            if count_within(mid) < k:
                lo = mid + 1
            else:
                hi = mid
        return lo

Why the answer is always a real distance
#

The search returns the first d with count >= k. If no pair had distance exactly d, then count(d) == count(d - 1), so d - 1 would also satisfy the condition, contradicting “first”. So the answer is always some pair’s distance.

Complexity
#

Time O(n log n + n log W), where W is the largest distance. Space O(1) excluding the sort.

Mistakes to Avoid
#

  • Listing every pair and sorting: O(n^2 log n).
  • Popping from a heap k times: k can reach 5 * 10^7.
  • Restarting left from the beginning for each right while counting: left must only move forward.

Interview Explanation
#

There are too many pairs to list, so I binary search the distance: the number of pairs with distance at most d is monotonic in d, and the first d where it reaches k is the answer. To count, I sort and slide a window: for each right end, push the left end until the gap is at most d, and add right - left. Each count is O(n), giving O(n log n + n log W) overall.

Related

LeetCode 2968: Apply Operations to Maximize Frequency Score
·2 mins
LeetCode Hard Sliding-Window Sorting Prefix-Sum Binary-Search Array
LeetCode 2968 note: after sorting, the cheapest common target for a block is its median; prefix sums give the cost in O(1), and it grows with the window, so slide
LeetCode 3323: Minimize Connected Groups by Inserting Interval
·2 mins
LeetCode Medium Sliding-Window Sorting Binary-Search Array
LeetCode 3323 note: merge first; a new interval can join groups l through r ⇔ start of group r − end of group l <= k, so a sliding window finds the most groups one interval can connect
LeetCode 2972: Count the Number of Incremovable Subarrays II
·2 mins
LeetCode Hard Two-Pointers Binary-Search Array
LeetCode 2972 note: what remains is a strictly increasing prefix plus suffix; for each valid prefix end, a right-only pointer finds the first suffix start that can follow it, and every later start works too
LeetCode 2302: Count Subarrays With Score Less Than K
·2 mins
LeetCode Hard Sliding-Window Prefix-Sum Binary-Search Array
LeetCode 2302 note: score = sum × length with positive numbers grows with the window; shrink while the score is >= k, and right - left + 1 valid subarrays end at right
LeetCode 1838: Frequency of the Most Frequent Element
·2 mins
LeetCode Medium Sliding-Window Sorting Greedy Prefix-Sum Binary-Search Array
LeetCode 1838 note: after sorting, raising the whole window to nums[right] costs nums[right] × length − window sum; shrink the left while that exceeds k
LeetCode 2271: Maximum White Tiles Covered by a Carpet
·2 mins
LeetCode Medium Sliding-Window Greedy Sorting Prefix-Sum Binary-Search Array
LeetCode 2271 note: starting the carpet at some segment’s start is never worse; after sorting, two pointers sum the fully covered segments and count the last one partially