Data Structures & AlgorithmsHardProduct Company SDE · ICPC regional

Consider the permutation p = [4, 1, 7, 3, 8, 2, 6, 5]. Count its inversions, i.e. pairs of positions i < j with p[i] > p[j]. Run the code.

Consider the permutation p = [4, 1, 7, 3, 8, 2, 6, 5]. Count its inversions, i.e. pairs of positions i < j with p[i] > p[j]. Run the code.
p=[4,1,7,3,8,2,6,5]
print(sum(1 for i in range(len(p)) for j in range(i+1,len(p)) if p[i]>p[j]))
What is printed?
  1. A. 6
  2. B. 16
  3. C. 4
  4. D. 12

Correct answer: D. 12

An inversion is a pair in the wrong order, so the count is over i < j with p[i] > p[j]. Counting only adjacent descents undercounts, and counting the non-inversion pairs gives the complement.

More Coding Interview Problems questions

Exams that ask this topic