Find K-th Smallest Pair Distance

The distance of a pair of integers `a` and `b` is `|a - b|`. Given an integer array `nums` and an integer `k`, return the `k`-th smallest distance among all pairs `nums[i]` and `nums[j]` with `0 <= i < j < nums.length`.

30:00

Find K-th Smallest Pair Distance
hard
Free written solution
Topics
Companies

The distance of a pair of integers a and b is |a - b|. Given an integer array nums and an integer k, return the k-th smallest distance among all pairs nums[i] and nums[j] with 0 <= i < j < nums.length.

Example 1:
Input: {"nums":[1,3,1],"k":1}
Output: 0
Constraints:
  • n==nums.lengthn == nums.\text{length}

  • 2≤n≤1042 \leq n \leq 10^4

  • 0≤nums[i]≤1060 \leq nums[i] \leq 10^6

  • 1≤k≤n(n−1)/21 \leq k \leq n(n-1)/2

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,3,1],"k":1}

candidate distance d: search range [lo, hi]

0lo 0 · hi 22

sorted nums

1

0

3

1

1

2

Input [1,3,1], k = 1. Distances do not depend on order, so sort first.

Variables
VariableValue
lo0
hi2
k1
DepthFunction Call
Stack empty
0/13