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
K-th Smallest Pair Distance INPUT Array nums: 1 i=0 3 i=1 1 i=2 k = 1 k = 1 All Valid Pairs (i < j): (0,1): |1-3| = 2 (0,2): |1-1| = 0 (1,2): |3-1| = 2 Distances: [2, 0, 2] ALGORITHM STEPS 1 Sort Array [1,3,1] --> [1,1,3] 2 Binary Search Setup lo=0, hi=max-min=2 3 Count Pairs For mid, count pairs with distance <= mid 4 Adjust Search If count >= k: hi=mid Else: lo=mid+1 Search Progress: mid=1: count=1 >=1 mid=0: count=1 >=1 lo=hi=0 --> DONE Result: 0 FINAL RESULT Sorted Distances: 0 2 2 1st 2nd 3rd Output: 0 The 1st smallest pair distance is 0 Winning Pair: nums[0]=1, nums[2]=1 |1 - 1| = 0 -- OK Key Insight: Binary search on the answer! Instead of computing all O(n^2) distances, binary search for the smallest distance d where at least k pairs have distance <= d. Use two pointers to count pairs in O(n) time per search iteration. Overall complexity: O(n log n + n log W) where W = max - min. TutorialsPoint - Find K-th Smallest Pair Distance | Optimal Solution (Binary Search)
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