Find K-th Smallest Pair Distance
Master this topic with zero to advance depth.
Find K-th Smallest Pair Distance
The distance of a pair of integers a and b is defined as the absolute difference between a and b. Given an integer array nums and an integer k, return the k-th smallest distance among all the pairs nums[i] and nums[j] where .
Examples
Level I: Brute Force (Iterate All Pairs)
Intuition
Calculate every possible pair distance, store them, and pick the -th smallest.
Detailed Dry Run
nums = [1,3,1], k=1 Distances: |1-3|=2, |1-1|=0, |3-1|=2. Sorted: [0, 2, 2]. Result: 0.
Level II: Min-Heap (Heap of Pairs)
Intuition
Sort the array. Adjacent pairs have the smallest gaps. Use a min-heap to explore larger gaps sequentially.
Detailed Dry Run
nums=[1,1,3], k=1 Heap: (0,1) dist 0, (1,2) dist 2. Pop (0,1). Result 0.
Level III: Optimal (Binary Search + Sliding Window)
Intuition
Binary search for the distance such that there are at least pairs with distance . Counting is done in using two pointers.
Detailed Dry Run
nums=[1,1,3], k=1. Sorted: [1,1,3]. L=0, R=2. Mid=1. Count=2 >= 1. R=1. L=0, R=1. Mid=0. Count=1 >= 1. R=0. Result 0.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.