Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: How many inversions does the array [4, 3, 2, 1, 0] have? Run the code.

Problem: How many inversions does the array [4, 3, 2, 1, 0] have? Run the code.
a = [4, 3, 2, 1, 0]
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. 9
  2. B. 10
  3. C. 8
  4. D. 15

Correct answer: B. 10

A strictly decreasing array of length 5 has every pair inverted, giving C(5,2) = 10.

More Coding Interview Problems questions

Exams that ask this topic