Skip to content
BytePatterns

Kth Smallest Pair Distance

HardSearching#binary-search-on-answer#two-pointers#sorting~35m

Problem

The distance of a pair of values is the absolute difference between them. Given a list of integers nums and an integer k, consider every pair of positions i < j and return the kth smallest distance among all of those pairs, counting from 1.

Examples

Input:  nums = [1, 3, 1], k = 1
Output: 0
Why:    the pair distances are 2, 0 and 2, and the smallest is 0
Input:  nums = [62, 100, 4], k = 2
Output: 58
Why:    the distances sorted are 38, 58 and 96
Input:  nums = [5, 5, 5], k = 3
Output: 0
Why:    edge case, equal values give three pairs at distance 0

Hints

0 / 3

Stuck on the idea rather than the code? Binary Search on Answer covers it.