Data Structures & AlgorithmsHardProduct Company SDE · counting

Problem: How many inversions (pairs i < j with a[i] > a[j]) does a = [2, 0, 2, 1, 1, 0] have? Run the code.

Problem: How many inversions (pairs i < j with a[i] > a[j]) does a = [2, 0, 2, 1, 1, 0] have? Run the code.
a = [2, 0, 2, 1, 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. 8
  3. C. 10
  4. D. 6

Correct answer: A. 9

Equal values are not inversions. Counting only pairs with the first element at index 0 gives 4, which is not the total.

More Coding Interview Problems questions

Exams that ask this topic