Data Structures & AlgorithmsVery hardLeetCode-style · Codeforces Div2 D

For the multiset [1, 6, 1, 9, 4, 12, 3], consider all unordered pairs of distinct positions and their absolute differences. What is the 6-th smallest difference (counted with multiplicity)?

  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 5

Correct answer: A. 3

Sort the array and binary search the difference d: count pairs with difference ≤ d with a two-pointer sweep, and find the smallest d whose count reaches k. Pairs with equal values have distance 0 and are counted with multiplicity, which shifts the index.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic