Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.
Example 1:
Input: nums = [1,3,1], k = 1 Output: 0 Explanation: Here are all the pairs: (1,3) -> 2 (1,1) -> 0 (3,1) -> 2 Then the 1st smallest distance pair is (1,1), and its distance is 0.
Example 2:
Input: nums = [1,1,1], k = 2 Output: 0
Example 3:
Input: nums = [1,6,1], k = 3 Output: 5
Constraints:
n == nums.length2 <= n <= 1040 <= nums[i] <= 1061 <= k <= n * (n - 1) / 2Problem summary: 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 kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Binary Search
[1,3,1] 1
[1,1,1] 2
[1,6,1] 3
find-k-pairs-with-smallest-sums)kth-smallest-element-in-a-sorted-matrix)find-k-closest-elements)kth-smallest-number-in-multiplication-table)k-th-smallest-prime-fraction)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #719: Find K-th Smallest Pair Distance
class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
int left = 0, right = nums[nums.length - 1] - nums[0];
while (left < right) {
int mid = (left + right) >> 1;
if (count(mid, nums) >= k) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
private int count(int dist, int[] nums) {
int cnt = 0;
for (int i = 0; i < nums.length; ++i) {
int left = 0, right = i;
while (left < right) {
int mid = (left + right) >> 1;
int target = nums[i] - dist;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
cnt += i - left;
}
return cnt;
}
}
// Accepted solution for LeetCode #719: Find K-th Smallest Pair Distance
func smallestDistancePair(nums []int, k int) int {
sort.Ints(nums)
n := len(nums)
left, right := 0, nums[n-1]-nums[0]
count := func(dist int) int {
cnt := 0
for i, v := range nums {
target := v - dist
left, right := 0, i
for left < right {
mid := (left + right) >> 1
if nums[mid] >= target {
right = mid
} else {
left = mid + 1
}
}
cnt += i - left
}
return cnt
}
for left < right {
mid := (left + right) >> 1
if count(mid) >= k {
right = mid
} else {
left = mid + 1
}
}
return left
}
# Accepted solution for LeetCode #719: Find K-th Smallest Pair Distance
class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
def count(dist):
cnt = 0
for i, b in enumerate(nums):
a = b - dist
j = bisect_left(nums, a, 0, i)
cnt += i - j
return cnt
nums.sort()
return bisect_left(range(nums[-1] - nums[0]), k, key=count)
// Accepted solution for LeetCode #719: Find K-th Smallest Pair Distance
struct Solution;
impl Solution {
fn smallest_distance_pair(mut nums: Vec<i32>, k: i32) -> i32 {
let n = nums.len();
nums.sort_unstable();
let mut lo = 0;
let mut hi = nums[n - 1] - nums[0];
while lo < hi {
let mi = lo + (hi - lo) / 2;
let mut count = 0;
let mut j = 1;
for i in 0..n - 1 {
while j < n && nums[j] - nums[i] <= mi {
j += 1;
}
count += j - 1 - i;
}
if count >= k as usize {
hi = mi;
} else {
lo = mi + 1;
}
}
lo
}
}
#[test]
fn test() {
let nums = vec![1, 3, 1];
let k = 1;
let res = 0;
assert_eq!(Solution::smallest_distance_pair(nums, k), res);
let nums = vec![62, 100, 4];
let k = 2;
let res = 58;
assert_eq!(Solution::smallest_distance_pair(nums, k), res);
}
// Accepted solution for LeetCode #719: Find K-th Smallest Pair Distance
function smallestDistancePair(nums: number[], k: number): number {
nums.sort((a, b) => a - b);
const n = nums.length;
let left = 0,
right = nums[n - 1] - nums[0];
while (left < right) {
let mid = (left + right) >> 1;
let count = 0,
i = 0;
for (let j = 0; j < n; j++) {
// 索引[i, j]距离nums[j]的距离<=mid
while (nums[j] - nums[i] > mid) {
i++;
}
count += j - i;
}
if (count >= k) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.