Data Structures & AlgorithmsModerateCodeforces Div2 C · TCS NQT

How many unordered pairs of positions (i < j) in [9, 1, 6, 14, 3, 11, 7] have an absolute difference of at most 4?

  1. A. 7
  2. B. 12
  3. C. 10
  4. D. 9

Correct answer: D. 9

Sort the array, then for each i use a two-pointer or binary search to count the j with a[j] − a[i] ≤ d; the sorted order makes each count contiguous. Off-by-one at the boundary (strict vs non-strict) changes the total.

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

Exams that ask this topic