Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: How many permutations of 1..5 have exactly 2 fixed points? Run the code.

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

Correct answer: A. 20

Choose the 2 fixed points in C(5,2) = 10 ways and derange the other 3 in D(3) = 2 ways: 20. 'At least 2' gives 31, permuting the other 3 freely gives 10 · 6 = 60, and 10 forgets the derangement factor.

More Coding Interview Problems questions

Exams that ask this topic