Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: How many permutations of 0..4 have exactly one inversion? Run the code.

Problem: How many permutations of 0..4 have exactly one inversion? Run the code.
from itertools import permutations
print(sum(1 for p in permutations(range(5)) if sum(1 for i in range(5) for j in range(i + 1, 5) if p[i] > p[j]) == 1))
What is printed?
  1. A. 5
  2. B. 4
  3. C. 10
  4. D. 3

Correct answer: B. 4

A permutation with exactly one inversion swaps one adjacent pair, and there are 4 adjacent pairs.

More Coding Interview Problems questions

Exams that ask this topic