15% off all plans & roadmaps Use code

See plans

Find K-th Smallest Pair Distance

Updated

TL;DR: You need the k-th smallest absolute difference among all pairs, and building every pair is too large. Sort the array, binary search the distance value, and count qualifying pairs with two pointers in linear time.

Problem

You are given an integer array nums. Return the k-th smallest distance among all of its pairs.

The distance of a pair (A, B) is the absolute difference between A and B.

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

The 1st smallest distance pair is (1,1), and its distance is 0.

Constraints

  • 2 <= nums.length <= 10^4
  • 0 <= nums[i] < 10^6
  • 1 <= k <= nums.length * (nums.length - 1) / 2

Constraints that matter

  • n up to 10^4 means about 5 * 10^7 pairs. Storing or sorting all of them is too expensive, so the answer has to come from counting.
  • Values below 10^6 bound every distance below 10^6. Binary search over that range needs about 20 rounds.
  • k can be as large as n * (n - 1) / 2, so the pair count can reach about 5 * 10^7. That fits in a 32-bit int. This keeps the Java, C++, C# and Go code safe.
  • The array is unsorted. Sorting costs O(n log n), which is small next to the pair count, and it makes the two-pointer count valid.

View on LeetCode

Hints

Hint 1

You need the k-th value in a list of n * (n - 1) / 2 numbers, and you do not want to build that list.

Hint 2

This is the solution a beginner writes first.

Solution

Intuition

You need the k-th value in a list of n * (n - 1) / 2 numbers, and you do not want to build that list. The pattern that fits is binary search on the answer. Instead of searching the array, you search the range of possible distances, from 0 up to the largest gap between any two values.

It is like a sorted line of runners, where the left pointer is a gate that only moves forward past runners too far behind the current one. Each runner is passed once, so the count takes one pass.

The move that makes this work is a counting question. For a guessed distance d, how many pairs have a distance at most d? That count never goes down as d grows, so the answer is the smallest d where the count reaches k.

Because the count only changes at real pair distances, that smallest d is always the distance of some actual pair.

Sorting makes the count cheap. In a sorted array, the partners of index right within distance d form a contiguous run just before right. As right moves forward, the start of that run never moves backward, so two pointers that only move forward count every qualifying pair in one pass.

Watch the pattern animation

Worked example

Input: nums = [5, 5, 5, 5, 5], k = 10
Output: 0
Explanation: All five values are equal, so each of the 10 pairs has distance 0. The 10th smallest distance is therefore 0.

Approach 1: Brute force

This is the solution a beginner writes first. It treats the problem as a list problem. Generate every pair, record its distance, sort the list, and read position k - 1.

The answer is correct because it literally lists every distance in sorted order. Its cost comes from the size of that list, which grows with the square of n.

Steps

  1. Create an empty list distances.
  2. For each index i from 0 to n - 1, loop j from i + 1 to n - 1.
  3. Append the absolute difference of nums[i] and nums[j] to distances.
  4. Sort distances in ascending order.
  5. Return distances[k - 1].

Dry run

Build the list on [5, 5, 5, 5, 5]. The pairs are (0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (1,4), (2,3), (2,4) and (3,4). Every pair holds the same value, so every distance is 0.

distances ends with ten zeros, which is already sorted. distances[k - 1] is distances[9], and that value is 0.

Complexity

TimeO(n^2 log n)
SpaceO(n^2)

Let n be the array length, and let m = n * (n - 1) / 2 be the number of pairs, which is about n^2 / 2. Generating the distances visits each pair once, so that step is O(m), which is O(n^2). Sorting m values costs O(m log m), and log m is about 2 log n, so the sort is O(n^2 log n). The list holds m integers, so the space is O(n^2).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def smallestDistancePair(self, nums: List[int], k: int) -> int:
        distances = []
        n = len(nums)
        for i in range(n):
            for j in range(i + 1, n):
                distances.append(abs(nums[i] - nums[j]))
        distances.sort()
        return distances[k - 1]

The Median and Kth of Two Sorted Arrays infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Median and Kth of Two Sorted Arrays

Part of Binary Search Patterns

Approach 2: Sort, then binary search with two pointersOptimalMedian and Kth of Two Sorted Arrays

What's slow. The brute force writes about n^2 / 2 values and then sorts them. With n up to 10^4, that is roughly 5 * 10^7 values. Most of the time and memory goes to the list, and the list is only a means to find one number.

The insight that fixes it. You need the rank of a value, not the list. Once the array is sorted, a count function can answer how many pairs have distance at most d in O(n). Binary search over the distance range then needs only about 20 count calls, so the pairs are never stored.

The search range is [0, nums[n - 1] - nums[0]]. Zero is the smallest possible distance. No distance can exceed the gap between the smallest and largest values. Each round keeps the half of the range that still contains the answer.

Why it is correct. The count of pairs within distance d never drops as d grows, so the search can safely discard the half that lacks the k-th value. Two pointers stay correct because nums[right] only grows, so any index too far from right is also too far from every later right. The answer is always a real pair distance since the count only changes at those values, so the returned low is exact.

Steps

  1. Sort nums in ascending order.
  2. Set low = 0 and high = nums[n - 1] - nums[0].
  3. While low < high, set mid = low + (high - low) / 2.
  4. Count pairs with distance at most mid: set left = 0, and for each right, move left forward while nums[right] - nums[left] > mid, then add right - left to the count.
  5. If the count is at least k, set high = mid. Otherwise set low = mid + 1.
  6. Return low.

Dry run

Sorting [5, 5, 5, 5, 5] changes nothing. Then low = 0 and high = nums[4] - nums[0] = 0. The loop test low < high is false, so no count runs, and the function returns 0.

SteplowhighCheckResult
Sort--nums = [5, 5, 5, 5, 5]already sorted
Init00high = nums[4] - nums[0]0
Loop test00low < high is falseskip loop
Return00none0

The loop never runs on this input, so the example does not show the counting step. The same method on nums = [1, 3, 1] with k = 1 does run the loop.

After sorting, nums = [1, 1, 3] and high = 3 - 1 = 2. For mid = 1, the count is 1: right = 1 adds 1, and right = 2 moves left to index 2 and adds 0. For mid = 0, the count is also 1.

Steplowhighmidcount(mid)Decision
102111 >= k, so high = 1
201011 >= k, so high = 0
300--loop ends, return 0

Complexity

TimeO(n log n + n log W), where W = nums[n - 1] - nums[0]
SpaceO(1) extra, beyond the in-place sort

Let n be the array length and W the largest gap, which is below 10^6. Sorting costs O(n log n) by the comparison-sort bound. Each count pass is O(n) because right and left each move at most n times. The search keeps at most half the remaining range per round, so there are at most about log2(W) + 1 rounds, at most 20 here, for a total of O(n log n + n log W). The loop uses a fixed set of integer variables, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def smallestDistancePair(self, nums: List[int], k: int) -> int:
        nums.sort()
        n = len(nums)
        low, high = 0, nums[-1] - nums[0]
        while low < high:
            mid = (low + high) // 2
            # Count pairs with distance <= mid using two pointers
            count = 0
            left = 0
            for right in range(n):
                while nums[right] - nums[left] > mid:
                    left += 1
                count += right - left
            if count >= k:
                high = mid
            else:
                low = mid + 1
        return low

Common mistakes

  • high = mid - 1 inside the count >= k branch. The value mid can itself be the k-th smallest distance, so it must stay in the range. Set high = mid.
  • low = mid inside the count < k branch. When high is low + 1, mid equals low, and the loop never moves forward. Set low = mid + 1.
  • Counting before nums.sort(). The left pointer assumes sorted order, so unsorted input gives wrong counts. Sort first, then count.
  • count += right - left + 1. This counts each element as a pair with itself and overcounts every step. Use count += right - left, because the pairs are the indices strictly before right.
  • JavaScript nums.sort() with no comparator. The default sort compares strings, so 10 comes before 9. Pass (a, b) => a - b in both the brute force and the optimal solution.

Edge cases

  • All values equal, such as [5, 5, 5, 5, 5] with k = 10. The answer is 0, and high starts at 0, so the loop body never runs.
  • Two values at the extremes, such as [0, 999999] with k = 1. The only pair has distance 999999, so the answer is 999999. The search range ends exactly at that value.
  • k equal to the total number of pairs, such as [1, 3, 1] with k = 3. The largest distance is nums[n - 1] - nums[0], which is 2. The answer is 2.
  • Duplicates with a small k, such as [1, 1, 1, 3] with k = 2. There are three pairs with distance 0, so the answer is 0.
  • Unsorted input, such as [10, 2, 9] with k = 2. The distances are 8, 1 and 7. Sorted, they are 1, 7 and 8, so the answer is 7. Sorting first is required.
  • The smallest input, [0, 0] with k = 1. The only pair has distance 0, and the answer is 0.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Find K-th Smallest Pair Distance, with how to answer them.

Unlock the follow-ups

Find K-th Smallest Pair Distance FAQ

What is the time complexity of Find K-th Smallest Pair Distance?

The optimal solution runs in O(n log n + n log W), where W is nums[n - 1] - nums[0], which is below 10^6. The brute force runs in O(n^2 log n) because it sorts all n * (n - 1) / 2 distances.

Why use binary search on the answer for Find K-th Smallest Pair Distance?

The number of pairs within distance d never decreases as d grows, so the answer is the smallest d where that count reaches k. Binary search finds that d in about 20 steps. Each step counts pairs in O(n) instead of listing them.

Can Find K-th Smallest Pair Distance be solved in O(1) extra space?

Yes, if sorting in place is allowed. The counting step needs only a few integer variables, and no list of pair distances is stored. Some sort implementations use O(log n) or O(n) scratch space, so the language matters for the exact total.

Why does the brute force fail for Find K-th Smallest Pair Distance?

With n = 10^4, the brute force stores about 5 * 10^7 distances. In 32-bit integers, that is roughly 200 MB, and sorting that many values takes far too long for an interview limit. The counting approach avoids both costs.

Why do I need a comparator when sorting in JavaScript?

JavaScript sorts arrays as strings by default, so the values 10 and 9 would be ordered incorrectly. Pass (a, b) => a - b to sort numbers by value. The binary search and counting depend on a correct numeric order.

Asked at

See which companies ask this — Pro

Practise it