Data Structures & AlgorithmsHardProduct Company SDE · Amazon OA

Problem: What is the number of inversions in the array [6, 2, 8, 1, 9, 4, 3, 7, 5]? (An inversion is a pair of indices i < j with a[i] > a[j].)

  1. A. 17
  2. B. 5
  3. C. 19
  4. D. 36

Correct answer: A. 17

Counting, for each element, the smaller values to its right gives 5 + 1 + 5 + 0 + 4 + 1 + 0 + 1 = 17 (merge sort does it in O(n log n)). Counting only adjacent descents gives 5, counting a[i] < a[j] gives 36 − 17 = 19, and 36 counts every pair.

More Coding Interview Problems questions

Exams that ask this topic