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?
- A. 20
- B. 31
- C. 60
- 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
- Problem: What is the number of steps for the Collatz sequence starting at 97 to reach 1? Run the code. python n = 97 c = 0 while n != 1: n…
- Problem: How many subsets of {1, 2, ..., 12} have an odd sum? Run the code. python print(sum(1 for m in range(1 << 12) if sum(i + 1 for i…
- Problem: What is the largest value of x such that x^3 <= 10^12 (integer cube root)? Run the binary search. python lo, hi = 0, 10 6 while…
- Problem: How many integers in [1, 1000] are divisible by 2 and 5 but not by 4? Run the code. python print(sum(1 for x in range(1, 1001) if…
- Problem: Which algorithm finds the convex hull of n points in O(n log n) by sorting and building lower and upper chains?
- Problem: What is the expected linear-time algorithm for the smallest enclosing circle of n points?