Find K-th Smallest Pair Distance — LeetCode 719 Python Solution
- Problem
- #719
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [1,3,1], k = 1
- Output
- 0
- Explanation
- Here are all the pairs:
Python solution
class Solution:
def smallestDistancePair(self, nums: List[int], k: int) -> int:
def count(dist):
cnt = 0
for i, b in enumerate(nums):
a = b - dist
j = bisect_left(nums, a, 0, i)
cnt += i - j
return cnt
nums.sort()
return bisect_left(range(nums[-1] - nums[0]), k, key=count)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 719. Find K-th Smallest Pair Distance is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 719. Find K-th Smallest Pair Distance?
- LeetCode 719. Find K-th Smallest Pair Distance is rated Hard on LeetCode.
- What is the time complexity of LeetCode 719. Find K-th Smallest Pair Distance?
- The Python solution on this page runs in O(n) (after optional sort O(n log n)).
- What is the space complexity of LeetCode 719. Find K-th Smallest Pair Distance?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 719. Find K-th Smallest Pair Distance cover?
- LeetCode 719. Find K-th Smallest Pair Distance is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.