Data Structures & AlgorithmsHardGATE CS · TCS NQT

How many index pairs i < j in [1, 3, 4, 7, 8, 10] satisfy |a[j] - a[i]| <= 3?

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

Correct answer: C. 7

Two pointers on the sorted array: pairs within 3 are (1,3), (1,4), (3,4), (4,7), (7,8), (7,10), (8,10) = 7. Checking only consecutive pairs gives 5, using < 3 drops the gap-3 pairs (4), and 15 counts all pairs.

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

Exams that ask this topic