Find K-th Smallest Pair Distance

HardBinary Searchbinary search on answer

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

The distance of a pair of integers a and b is |a - b|. Given an integer array nums and an integer k, consider all pairs (nums[i], nums[j]) with 0 <= i < j < nums.length. Return the k-th smallest distance among all these pairs (1-indexed, counting duplicate distances separately). Aim for O(n log n + n log W), where W is the range of values.

Examples

Input: nums = [1,3,1], k = 1
Output: 0
The distances are 2, 0, 2; the smallest is 0.
Input: nums = [1,1,1], k = 2
Output: 0
All three pairs have distance 0.
Input: nums = [1,6,1], k = 3
Output: 5
The distances sorted are 0, 5, 5; the third is 5.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More binary search on answer problems