Data Structures & AlgorithmsModerateProduct Company SDE · merge-sort counting round

Problem: Count the inversions of the array [3, 1, 4, 1, 5, 9, 2, 6], where an inversion is a pair of positions i < j with a[i] > a[j] (equal values do not count).

  1. A. 9
  2. B. 8
  3. C. 3
  4. D. 19

Correct answer: B. 8

Pairs with a larger value first: 3 → (1, 1, 2), 4 → (1, 2), 5 → (2), 9 → (2, 6), totalling 8. Counting the equal pair (1, 1) gives 9, counting only adjacent descents (one bubble pass) gives 3, and counting a[i] < a[j] instead gives 19.

More Coding Interview Problems questions

Exams that ask this topic