Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

The k-th smallest distance between two values

Hard · Target 30 minutes · Binary search · Type asked atGoogleTwo SigmaCitadel

The distance of a pair of values a, b is |a − b|. Given an array nums, return the k-th smallest distance among all pairs nums[i], nums[j] with i < j, counting repeats.

Examples

InputOutputWhy
nums = [1, 3, 1], k = 10Distances: 2, 0, 2. The smallest is 0.
nums = [1, 1, 1], k = 20
nums = [1, 6, 1], k = 35Distances: 5, 0, 5.

Constraints

  • 2 ≤ n ≤ 10⁴
  • 0 ≤ nums[i] ≤ 10⁶
  • 1 ≤ k ≤ n(n − 1)/2

Hints

Hint 1

Listing all distances is up to 5 × 10⁷ values. Instead, for a distance d, can you count the pairs at distance ≤ d quickly?

Hint 2

Sort the array. For each right end hi, the values within d of nums[hi] on its left form a window [lo, hi − 1], and lo only moves right as hi does.

Hint 3

That count is non-decreasing in d. Search d in [0, max − min] for the first d whose count is at least k.

Where people lose marks

  • Counting pairs with a nested loop inside the search: O(n² log W), too slow at n = 10⁴.
  • Moving lo back to 0 for each hi, which also makes the count quadratic.
  • Counting each pair twice (as i, j and j, i), or counting a value paired with itself.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.