Data Structures & AlgorithmsHardProduct Company SDE · counting

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

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

Correct answer: D. 6

5 beats all four later values and 4 beats 2 and 3, giving 6 inversions. Adjacent descents give 2, 10 is all pairs, and the 4 increasing pairs are the complement.

More Coding Interview Problems questions

Exams that ask this topic