Find K-th Smallest Pair Distance - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,1], k = 1
Output: 0
💡 Note: All pairs and their distances: (1,3)→2, (1,1)→0, (3,1)→2. Sorted distances: [0,2,2]. The 1st smallest is 0.
Example 2 — Second Smallest
$ Input: nums = [1,1,1], k = 2
Output: 0
💡 Note: All pairs have the same values, so all distances are 0. The 2nd smallest distance is still 0.
Example 3 — Larger Array
$ Input: nums = [1,6,1], k = 3
Output: 5
💡 Note: Pairs: (1,6)→5, (1,1)→0, (6,1)→5. Sorted: [0,5,5]. The 3rd smallest is 5.

Constraints

  • n == nums.length
  • 2 ≤ n ≤ 104
  • 0 ≤ nums[i] ≤ 106
  • 1 ≤ k ≤ n(n-1)/2

Visualization

Tap to expand
Find K-th Smallest Pair DistanceInput Array:131k = 1All Pair Distances:|1-3|=2|1-1|=0|3-1|=2Distances: [2, 0, 2]Sorted: [0, 2, 2]0221st2nd3rdOutput: 0The 1st smallest distance is 0
Understanding the Visualization
1
Input
Array nums and integer k
2
Process
Calculate all pair distances or use binary search
3
Output
Return the kth smallest distance
Key Takeaway
🎯 Key Insight: Binary search on answer space with two-pointer counting is much more efficient than generating all O(n²) pairs
Asked in
Google 15 Facebook 12 Amazon 8
85.0K Views
Medium Frequency
~35 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen