Data Structures & AlgorithmsModerateTCS NQT Digital · Infosys

Problem: Count the pairs (i, j) with i < j in the array [1, 5, 2, 8, 3, 5] whose absolute difference is at most 2.

  1. A. 3
  2. B. 6
  3. C. 1
  4. D. 12

Correct answer: B. 6

Sorting [1, 2, 3, 5, 5, 8] and sliding a window finds (1,2), (1,3), (2,3), (3,5), (3,5), (5,5): 6 pairs. Using < 2 gives 3, checking only adjacent positions in the original order gives 1, and counting ordered pairs gives 12.

More Coding Interview Problems questions

Exams that ask this topic