Find K-th Smallest Pair Distance

Try to solve the Find K-th Smallest Pair Distance problem.

Statement

Given an array of integers nums and an integer k, return the kthk^{th} smallest distance between any pair of integers (nums[i], nums[j]), where 00 \leq i << j << num.length.

The distance between a pair of integers, aa and bb, is defined as the absolute difference between them.

Constraints:

  • n==n == nums.length

  • 2n1032 \leq n \leq 10^3

  • 00 \leq nums[i] 103\leq 10^3

  • 11 \leq k n×(n1)2\leq \frac{n \times (n-1)}{2}

Note: Given an array of size nn, the total number of possible pairs is given by nC2{}^{n}C_{2}. As nC2{}^{n}C_{2} evaluates to n×(n1)2\frac{n \times (n-1)}{2}, there are exactly these much possible kk-distances.

Examples

Press + to interact
canvasAnimation-image
1 of 3

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

1

What is the output if the following array and k = 8 are given as input?

nums = [7, 5, 3, 11, 2]

A)

66

B)

88

C)

99

D)

The input is invalid.

Question 1 of 40 attempted

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Try it yourself

Implement your solution in the following coding playground.

Press + to interact
Java
usercode > Solution.java
public class Solution {
public static int smallestDistancePair(int[] nums, int k) {
// Replace this placeholder return statement with your code
return -1;
}
}
Find K-th Smallest Pair Distance

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.