Data Structures & AlgorithmsHard

Count the inversions of [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]: pairs of positions i < j with N[i] > N[j]. Equal values are not inversions.

  1. A. 17
  2. B. 22
  3. C. 5
  4. D. 33

Correct answer: A. 17

An inversion needs a strictly larger value before a smaller one. Using ≥ counts equal pairs as inversions, counting only adjacent pairs misses non-adjacent inversions, and counting the opposite order gives the non-inversions instead.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic