Data Structures & AlgorithmsModerateTCS NQT · Accenture

Problem: In the sorted array [1, 2, 4, 7, 8, 11, 13], how many pairs (i, j) with i < j have a[j] − a[i] ≤ 2?

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

Correct answer: D. 4

Because the array is sorted, the differences grow with the gap, so a two-pointer sweep works. Checking only adjacent elements misses pairs such as (2, 4) that are not neighbours.

More Coding Interview Problems questions

Exams that ask this topic