Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many inversions does [9, 7, 5, 3, 1, 2, 4, 6, 8] have? Run the code.

Problem: How many inversions does [9, 7, 5, 3, 1, 2, 4, 6, 8] have? Run the code.
a = [9, 7, 5, 3, 1, 2, 4, 6, 8]
print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if a[i] > a[j]))
What is printed?
  1. A. 4
  2. B. 20
  3. C. 36
  4. D. 16

Correct answer: B. 20

9, 7, 5, 3 contribute 8 + 6 + 4 + 2 = 20 inversions and 1 has none. Counting adjacent descents gives 4, 36 is all pairs, and 16 counts the non-inverted pairs.

More Coding Interview Problems questions

Exams that ask this topic