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.
Example 1:
Input: nums = [1,3,1], k = 1 Output: 0 Explanation: Here are all the pairs: (1,3) -> 2 (1,1) -> 0 (3,1) -> 2 Then the 1st smallest distance pair is (1,1), and its distance is 0.
Example 2:
Input: nums = [1,1,1], k = 2 Output: 0
Example 3:
Input: nums = [1,6,1], k = 3 Output: 5
Constraints:
n == nums.length2 <= n <= 1040 <= nums[i] <= 1061 <= k <= n * (n - 1) / 2This approach utilizes sorting and a min-heap (or priority queue) to efficiently manage and retrieve the k-th smallest distance. The key steps are:
nums. This simplifies the process of finding the distances as all distance calculations will involve consecutive elements.First, the array is sorted to enable orderly distance calculations. A min-heap (priority queue) is used to efficiently manage the distances and extract the k-th smallest. After computing and storing distances in the heap, we extract the smallest k elements, finally returning the k-th one.
C++
Time Complexity: O(n^2 log n) due to the double loop and heap operations.
Space Complexity: O(n^2) for storing all possible distances in the heap.
This more efficient approach combines binary search with a two-pointer technique. The principal idea is to use binary search over distance values to pinpoint the k-th smallest distance. It involves:
nums.This solution involves a binary search to determine the smallest possible distance. The associated helper function utilizes a two-pointer technique to count how many pairs have distances less than a proposed distance during the search process. Adjusting the binary search bounds based on this count homes in on the k-th smallest.
C++
Java
Time Complexity: O(n log n + n log(maxDistance))
Space Complexity: O(1) as no additional space beyond fixed variables is used.
| Approach | Complexity |
|---|---|
| Approach 1: Sort and Use a Min-Heap | Time Complexity: O(n^2 log n) due to the double loop and heap operations. |
| Approach 2: Binary Search on Distance Combined with Two-pointers | Time Complexity: O(n log n + n log(maxDistance)) |
Find K-th Smallest Pair Distance - Leetcode 719 - Python • NeetCodeIO • 17,861 views views
Watch 9 more video solutions →Practice Find K-th Smallest Pair Distance with our built-in code editor and test cases.
Practice on FleetCode