Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Count the number of ways to assign n distinct tasks to n workers where task i cannot go to worker i (derangements), modulo 10⁹ + 7.
Problem: Count the number of ways to assign n distinct tasks to n workers where task i cannot go to worker i (derangements), modulo 10⁹ + 7.
def derange(n, M=10**9 + 7):
a, b = 1, 0 # D(0), D(1)
if n == 0: return 1
for i in range(2, n + 1):
a, b = b, (i - 1) * (a + b) % M
return b
print(derange(3), derange(4), derange(5), derange(1))What is printed?- A. 2 9 44 1
- B. 2 9 44 0
- C. 3 9 44 0
- D. 2 8 44 0
Correct answer: B. 2 9 44 0
D(n) = (n − 1)(D(n − 1) + D(n − 2)): place item 1 at position k (n − 1 choices), then item k either swaps back (D(n − 2)) or not (D(n − 1)). Sequence 1, 0, 1, 2, 9, 44. One task cannot avoid its own worker → 0. O(n).
More Coding Interview Problems questions
- Problem: Reconstruct a queue of people (h, k) where k = number of people in front with height ≥ h. python def rebuild(people)…
- Problem: Find the minimum number of refuelling stops to travel a distance, given stations (position, fuel) and start fuel. python import…
- Problem: A printer raises ink levels by choosing any contiguous block of cartridges and adding 1 unit to each in one operation. Starting…
- Problem: Count contiguous subarrays whose max − min ≤ k, using two monotonic deques and a shrinking left edge. python from collections…
- Problem: Return the k-th smallest absolute difference among all pairs of readings (n up to 10⁵, so the n² pairs cannot be listed). Binary…
- Problem: Tasks of given lengths must be packed into work sessions of at most T = 8 hours; a task cannot be split. Exact bitmask DP (state…