Data Structures & AlgorithmsHardProduct company OA · Amazon/Microsoft-style OA

Sorted array [2, 3, 7, 9, 12, 15, 18]. How many index pairs i < j have a difference srt[j] - srt[i] in the range (3, 8], i.e. greater than 3 and at most 8?

  1. A. 9
  2. B. 6
  3. C. 8
  4. D. 11

Correct answer: C. 8

Count pairs with difference at most 8 and subtract those with difference at most 3, using two pointers for each bound. Including difference exactly 3 in the subtraction is the usual off-by-one trap.

More Coding Interview Problems questions

Exams that ask this topic