ntree.ai
ntree.aiFind K-th Smallest Pair Distance

Solutions

1. Brute Force

O(n²logn) time | O(n²) space

Intuition

We can take the distance of every pair, sort all of them and return the k-th element.

Algorithm

  1. Create an empty array for the distances.
  2. Iterate through the outer loop from the first element to the last element with i index.
  3. For each outer loop iteration, iterate through the inner loop from the element at i + 1 to the last element with j index, and add the distance between the two elements to the array.
  4. Sort the array.
  5. Return the element at index k - 1.
k = 3
1
6
1
4
0123
i j
|1 − 6| = 5, add 5
1 / 8

Code

Code
Python
def smallestDistancePair(nums: list[int], k: int) -> int:
distances = []
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
distances.append(abs(nums[i] - nums[j]))
distances.sort()
return distances[k - 1]
/**
* @param {number[]} nums
* @param {number} k
* @returns {number}
*/
var smallestDistancePair = function (nums, k) {
const distances = []
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
distances.push(Math.abs(nums[i] - nums[j]))
}
}
distances.sort((a, b) => a - b)
return distances[k - 1]
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Solution {
public int smallestDistancePair(int[] nums, int k) {
List<Integer> distances = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
distances.add(Math.abs(nums[i] - nums[j]));
}
}
Collections.sort(distances);
return distances.get(k - 1);
}
}

2. Heap

O(nlogn + klogn) time | O(n) space

Intuition

If we sort the array first, the smallest distance will be between some of two neighbours. The second smallest distance is either between another two neighbours, or one element to the right of the smallest pair.

If we put every distance in a table with a row for each i index and a column for each j index for the sorted array [1, 1, 4, 6], the smallest distance left in a row is always the leftmost one we have not taken yet.

j = 1j = 2j = 3
i = 0035
i = 135
i = 22

If we keep a heap of only the leftmost distance of every row, the k-th distance we take from the heap is the answer.

Algorithm

  1. Sort the array.
  2. Create a min heap with the distance of every pair of neighbours and the two indexes it was measured between.
  3. Iterate through the loop k - 1 times.
    • Pop the smallest pair from the heap.
    • Push the distance between the element at the same first index and the element after the second index.
  4. Return the distance on top of the heap.
k = 3
1
1
4
6
0123
i j
1 − 1 = 0, push 0
1 / 6

Code

Code
Python
import heapq
def smallestDistancePair(nums: list[int], k: int) -> int:
nums.sort()
pairs = [(nums[i + 1] - nums[i], i, i + 1) for i in range(len(nums) - 1)]
heapq.heapify(pairs)
for _ in range(k - 1):
distance, i, j = heapq.heappop(pairs)
if j + 1 < len(nums):
heapq.heappush(pairs, (nums[j + 1] - nums[i], i, j + 1))
return pairs[0][0]
/**
* @param {number[]} nums
* @param {number} k
* @returns {number}
*/
var smallestDistancePair = function (nums, k) {
nums.sort((a, b) => a - b)
const pairs = new MinPriorityQueue()
for (let i = 0; i + 1 < nums.length; i++) pairs.push([nums[i + 1] - nums[i], i, i + 1])
for (let taken = 1; taken < k; taken++) {
const [, i, j] = pairs.pop()
if (j + 1 < nums.length) pairs.push([nums[j + 1] - nums[i], i, j + 1])
}
return pairs.top()[0]
}
class MinPriorityQueue {
constructor() {
this.values = []
}
top() {
return this.values[0]
}
push(value) {
this.values.push(value)
let at = this.values.length - 1
while (at > 0) {
const parent = (at - 1) >> 1
if (this.values[parent][0] <= this.values[at][0]) break
this.swap(parent, at)
at = parent
}
}
pop() {
const top = this.values[0]
this.values[0] = this.values[this.values.length - 1]
this.values.pop()
let at = 0
for (;;) {
let smallest = at
for (const child of [at * 2 + 1, at * 2 + 2]) {
if (child < this.values.length && this.values[child][0] < this.values[smallest][0]) smallest = child
}
if (smallest === at) return top
this.swap(smallest, at)
at = smallest
}
}
swap(a, b) {
const held = this.values[a]
this.values[a] = this.values[b]
this.values[b] = held
}
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
PriorityQueue<int[]> pairs = new PriorityQueue<>(Comparator.comparingInt(pair -> pair[0]));
for (int i = 0; i + 1 < nums.length; i++) pairs.offer(new int[] { nums[i + 1] - nums[i], i, i + 1 });
for (int taken = 1; taken < k; taken++) {
int[] pair = pairs.poll();
int i = pair[1], j = pair[2];
if (j + 1 < nums.length) pairs.offer(new int[] { nums[j + 1] - nums[i], i, j + 1 });
}
return pairs.peek()[0];
}
}

3. Binary Search with Sliding Window

O(nlogn + nlogd) time | O(1) space, for the greatest distance d

Intuition

We can use the binary search technique, starting from the average of the smallest and the greatest distance instead of checking every distance.

At each step we count how many pairs have a distance no greater than that average. When there are k or more of them, the k-th smallest distance is somewhere between the smallest distance and the average. Otherwise it is greater than the average, so the answer is between the average and the greatest distance.

To count the pairs we use a sliding window technique on a sorted array. We keep a window between the left and right indexes, and extend it by moving right one element forward. When the distance of the two elements is greater than the average, we move left forward until it is not.

When we move right forward, left never goes back towards the start, because the elements only grow, so every window that starts before it has a distance greater than the average. Then at every right index the window is every element whose distance to the one at right is no greater than the average, so it adds right - left pairs to the count.

Algorithm

  1. Sort the array.
  2. Create low and high integer variables with 0 and the distance between the last and the first element as initial values.
  3. While low is less than high, take the middle of low and high as the average.
    • Count the pairs with a distance no greater than the average: walk the array with right index, move left forward while the distance between the elements at left and right is greater than the average, and add right - left to the count on each step.
    • Set high to the average when the count is k or greater, otherwise set low to the average plus one.
  4. Return low.
k = 3
1
1
4
6
0123
leftright
low = 0, high = 5, average = 2, distance = 0, 0 ≤ 2, no greater distances = 0
1 / 19

Code

Code
Python
def smallestDistancePair(nums: list[int], k: int) -> int:
nums.sort()
low, high = 0, nums[-1] - nums[0]
while low < high:
average = (low + high) // 2
if smallerDistances(nums, average) >= k:
high = average
else:
low = average + 1
return low
def smallerDistances(nums: list[int], distance: int) -> int:
count = 0
left = 0
for right in range(len(nums)):
while nums[right] - nums[left] > distance:
left += 1
count += right - left
return count
/**
* @param {number[]} nums
* @param {number} k
* @returns {number}
*/
var smallestDistancePair = function (nums, k) {
nums.sort((a, b) => a - b)
let low = 0
let high = nums[nums.length - 1] - nums[0]
while (low < high) {
const average = Math.floor((low + high) / 2)
if (smallerDistances(nums, average) >= k) high = average
else low = average + 1
}
return low
}
var smallerDistances = function (nums, distance) {
let count = 0
let left = 0
for (let right = 0; right < nums.length; right++) {
while (nums[right] - nums[left] > distance) left++
count += right - left
}
return count
}
import java.util.Arrays;
class Solution {
public int smallestDistancePair(int[] nums, int k) {
Arrays.sort(nums);
int low = 0;
int high = nums[nums.length - 1] - nums[0];
while (low < high) {
int average = (low + high) / 2;
if (smallerDistances(nums, average) >= k) high = average;
else low = average + 1;
}
return low;
}
private int smallerDistances(int[] nums, int distance) {
int count = 0;
int left = 0;
for (int right = 0; right < nums.length; right++) {
while (nums[right] - nums[left] > distance) left++;
count += right - left;
}
return count;
}
}
Was the explanation clear?
def smallestDistancePair(nums: list[int], k: int) -> int:
pass
 

Press Visualise to step through your code.