You are given an integer array nums[]. The distance between a pair of elements is defined as the absolute difference between their values. Your task is to find the kth smallest distance among all possible pairs in the array.
Example 1
Input: nums = [1,3,1], k = 1
Output: 0
Explanation: All possible pairs are (1,3), (1,1), and (3,1). Their distances are 2, 0, and 2. The sorted distances are [0,2,2]. The 1st smallest distance is 0.
Example 2
Input: nums = [1,6,1], k = 3
Output: 5
Explanation: All possible pairs are (1,6), (1,1), and (6,1). Their distances are 5, 0, and 5. The sorted distances are [0,5,5]. The 3rd smallest distance is 5.
Example 3
Input: nums = [1,2,3,4], k = 4
Output: 2
Explanation: All possible pairs are (1,2), (1,3), (1,4), (2,3), (2,4), (3,4). Their distances are 1, 2, 3, 1, 2, and 1. The sorted distances are [1,1,1,2,2,3]. The 4th smallest distance is 2.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
1 3 1 1
1
1 3 1 2
2
1 6 1 3
5