Find K-th Smallest Pair Distance — LeetCode 719 Python Solution

HardArrayTwo PointersBinary SearchSorting
Problem
#719
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview