Editorial
Core insight
Find K-th Smallest Pair Distance · Binary Search Patterns
Core Insight for Find K-th Smallest Pair Distance
The key to solving LeetCode 719 efficiently lies in realizing that we do not need to compute all pairs to know how many pairs are "small enough."
If we sort the input array nums first, the minimum possible distance is 0 (if duplicates exist) or the smallest adjacent difference. The maximum possible distance is nums[n-1] - nums[0]. The answer must lie within this range .
Instead of searching for the pair itself, we binary search for the answer. Let's guess a distance mid. Can we calculate how many pairs have a distance less than or equal to mid efficiently?
If we can count these pairs in time, we can determine if our guess mid is too small (count ) or potentially large enough (count ). This reduces the complexity significantly.
Visual Description:
Imagine the search space as a horizontal axis representing all possible distance values from 0 to the maximum difference. We place a marker mid in the center. We then iterate through the sorted array nums. For every element nums[right], we visualize a window extending backwards to nums[left] such that the difference nums[right] - nums[left] fits within our mid marker. The size of this window (right - left) represents the number of valid pairs ending at right. We sum these window sizes. If the total sum is less than k, we discard the left half of our distance axis (values are too strict). If the sum is greater than or equal to k, we discard the right half (we might find a smaller valid distance), narrowing our search until we converge on the exact K-th distance.
Deep dive
Full breakdown
Full reasoning, pitfalls, and implementation flow
LeetCode 719: Find K-th Smallest Pair Distance Solution & Explanation
Problem Overview
TL;DR: The optimal solution uses binary search on the answer (the distance value) combined with a sliding window approach to efficiently count pairs, avoiding the generation of all possible pairs.
The Find K-th Smallest Pair Distance problem asks us to determine the -th smallest absolute difference between any two elements in a given integer array nums. If we were to calculate the absolute difference for every unique pair and sort these differences in ascending order, we need to return the value at the -th index (0-indexed).
This is a classic "K-th value" problem that requires optimizing beyond simple enumeration, making LeetCode 719 a popular interview question for testing algorithm optimization skills.
Brute Force Approach for Find K-th Smallest Pair Distance
The most intuitive way to solve this problem is to generate every possible pair, calculate their distances, store them, and sort the results.
- Initialize an empty list
distances. - Iterate through the array with two loops:
ifrom0ton-1andjfromi+1ton-1. - Calculate
abs(nums[i] - nums[j])and append it todistances. - Sort the
distanceslist. - Return the element at index
k-1.
1# Pseudo-code for Brute Force
2def smallestDistancePair(nums, k):
3 distances = []
4 n = len(nums)
5 for i in range(n):
6 for j in range(i + 1, n):
7 distances.append(abs(nums[i] - nums[j]))
8 distances.sort()
9 return distances[k-1]Why this fails: The time complexity of this approach is dominated by the number of pairs. For an array of size , there are pairs, which is . Sorting these pairs takes . Given the constraint , can reach . Sorting elements will inevitably result in a Time Limit Exceeded (TLE) error. Additionally, storing all pairs consumes memory, which may cause a Memory Limit Exceeded error.
Algorithm Strategy: Binary Search Patterns
- Sort the Input: First, sort
nums. This allows us to use a sliding window approach to count pairs and easily determine the maximum possible distance. - Define Search Space:
low= 0 (absolute difference is non-negative).high=nums[n-1] - nums[0](maximum possible difference).
- Binary Search Loop:
- While
low < high:- Calculate
mid = low + (high - low) // 2. - Count Pairs: Use a helper logic (Sliding Window) to count how many pairs satisfy
nums[j] - nums[i] <= mid. - Adjust Bounds:
- If
count < k: We need more pairs, so the distance limit must be higher. Setlow = mid + 1. - If
count >= k: We have enough pairs. Thismidcould be the answer, or the answer could be smaller. Sethigh = mid.
- If
- Calculate
- While
- Return: When
lowmeetshigh, we have found the smallest distance for which there are at leastkpairs. Returnlow.
Sliding Window Logic (The Counting Step):
Since nums is sorted, for a fixed index right, as we decrease index left, the difference nums[right] - nums[left] increases. We want the smallest left such that nums[right] - nums[left] <= mid. All indices between left and right form valid pairs with right. The number of such pairs is right - left. We sum this for all right from 0 to n-1.
Execution Flow
Let nums = [1, 3, 1] and k = 1.
- Preprocessing: Sort
nums. Newnums = [1, 1, 3]. - Initialization:
low = 0high = 3 - 1 = 2
- Iteration 1:
mid = (0 + 2) // 2 = 1.- Count Pairs (
<= 1):right = 0(val 1):leftstarts at 0. Diff 0 <= 1. Pairs: 0.right = 1(val 1):leftis 0. Diff . Pairs +=1 - 0= 1.right = 2(val 3):leftmoves to 2 (since ). Diff . Pairs +=2 - 2= 0.- Total count = 1.
- Check: Count (1) (1). This distance is valid, but maybe a smaller one exists.
high = mid = 1.
- Iteration 2:
low = 0,high = 1.mid = (0 + 1) // 2 = 0.- Count Pairs (
<= 0):right = 0: Pairs += 0.right = 1: . Pairs += 1.right = 2: ,leftmoves to 2. Pairs += 0.- Total count = 1.
- Check: Count (1) (1).
high = mid = 0.
- Termination:
low = 0,high = 0. Loop terminates.- Return
0.
Proof of Correctness
The correctness relies on the monotonicity of the problem. Let be the number of pairs with distance less than or equal to .
- If , then .
- We want the smallest such that .
Our binary search maintains the invariant that the answer lies within [low, high].
- If
count(mid) < k, thenmidis strictly too small. The answer must be , so we setlow = mid + 1. - If
count(mid) >= k, thenmidis a potential candidate (it has enough pairs covering it), but there might be a smaller valid distance. We keepmidin the search space by settinghigh = mid. - The loop terminates when
low == high, converging on the smallest distance satisfying the condition.
Pattern Reuse Notes
The Binary Search Patterns applied here are highly versatile. The specific subpattern of searching the value space to find a K-th element appears in:
- LeetCode 4: Median of Two Sorted Arrays: Uses binary search on the partition cuts (indices) or values to handle two arrays simultaneously.
- LeetCode 378: Kth Smallest Element in a Sorted Matrix: Identical strategy. We binary search the value range of the matrix elements and count how many elements are to determine rank.
Understanding LeetCode 719 solidifies the technique of "Binary Search on Answer," a powerful tool for optimization problems where the answer space is monotonic.
Feynman coach · Before you peek at the code
Can you explain the core insight in your own words?
If you can explain it before reading code, you’re far more likely to recall it under interview pressure.
Reference Implementation
C++ Solution for LeetCode 719
1#include <vector>
2#include <algorithm>
3#include <cmath>
4
5class Solution {
6public:
7 int smallestDistancePair(std::vector<int>& nums, int k) {
8 std::sort(nums.begin(), nums.end());
9
10 int n = nums.size();
11 int low = 0;
12 int high = nums[n - 1] - nums[0];
13
14 while (low < high) {
15 int mid = low + (high - low) / 2;
16
17 // Count pairs with distance <= mid
18 int count = 0;
19 int left = 0;
20 for (int right = 0; right < n; ++right) {
21 while (nums[right] - nums[left] > mid) {
22 left++;
23 }
24 count += (right - left);
25 }
26
27 // Binary Search Logic
28 if (count < k) {
29 low = mid + 1;
30 } else {
31 high = mid;
32 }
33 }
34
35 return low;
36 }
37};Java Solution for LeetCode 719
1import java.util.Arrays;
2
3class Solution {
4 public int smallestDistancePair(int[] nums, int k) {
5 Arrays.sort(nums);
6
7 int n = nums.length;
8 int low = 0;
9 int high = nums[n - 1] - nums[0];
10
11 while (low < high) {
12 int mid = low + (high - low) / 2;
13
14 // Count pairs with distance <= mid
15 int count = 0;
16 int left = 0;
17 for (int right = 0; right < n; right++) {
18 while (nums[right] - nums[left] > mid) {
19 left++;
20 }
21 count += (right - left);
22 }
23
24 // Binary Search Logic
25 if (count < k) {
26 low = mid + 1;
27 } else {
28 high = mid;
29 }
30 }
31
32 return low;
33 }
34}Python Solution for LeetCode 719
1class Solution:
2 def smallestDistancePair(self, nums: List[int], k: int) -> int:
3 nums.sort()
4
5 n = len(nums)
6 low = 0
7 high = nums[-1] - nums[0]
8
9 while low < high:
10 mid = (low + high) // 2
11
12 # Count pairs with distance <= mid
13 count = 0
14 left = 0
15 for right in range(n):
16 while nums[right] - nums[left] > mid:
17 left += 1
18 count += (right - left)
19
20 # Binary Search Logic
21 if count < k:
22 low = mid + 1
23 else:
24 high = mid
25
26 return low