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

Array a = [6, 1, 8, 3, 9, 4, 2, 7, 5] has distinct values. How many ordered pairs (i, j) with i != j satisfy a[i] - a[j] = 4?

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

Correct answer: C. 5

Store the values in a set and, for each x, check whether x - 4 is present; each hit is one ordered pair (i, j). The difference is positive in one direction only, so no pair is counted twice.

More Coding Interview Problems questions

Exams that ask this topic