Data Structures & AlgorithmsVery hardProduct company OA

Problem: Return the k-th smallest absolute difference among all pairs of readings (n up to 10⁵, so the n² pairs cannot be listed). Binary search on the answer d, counting pairs with difference ≤ d by two pointers.

Problem: Return the k-th smallest absolute difference among all pairs of readings (n up to 10⁵, so the n² pairs cannot be listed). Binary search on the answer d, counting pairs with difference ≤ d by two pointers.
def kth_pair_dist(a, k):
    a = sorted(a)
    def pairs_le(d):
        c = j = 0
        for i in range(len(a)):
            while a[i] - a[j] > d: j += 1
            c += i - j
        return c
    lo, hi = 0, a[-1] - a[0]
    while lo < hi:
        mid = (lo + hi) // 2
        if pairs_le(mid) >= k: hi = mid
        else: lo = mid + 1
    return lo
a = [9, 1, 6, 3, 14, 6]
print(kth_pair_dist(a, 1), kth_pair_dist(a, 5), kth_pair_dist(a, 15))
What is printed?
  1. A. 0 2 13
  2. B. 1 3 13
  3. C. 0 3 13
  4. D. 0 3 8

Correct answer: C. 0 3 13

pairs_le(d) is non-decreasing in d, so the smallest d with pairs_le(d) ≥ k is the k-th smallest distance – and it is always an actual distance. Sorted: [1, 3, 6, 6, 9, 14]. d = 0 already has one pair (6, 6). Distances sorted: 0, 2, 3, 3, 3, … so the 5th is 3. With 15 pairs the 15th is the maximum, 14 − 1 = 13. O(n log n + n log(range)).

More Coding Interview Problems questions

Exams that ask this topic