Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

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

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

Correct answer: D. 5

Each element is compared with the smaller values after it; the count of inversions is 5.

More Coding Interview Problems questions

Exams that ask this topic