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?
  1. A. 2 9 44 1
  2. B. 2 9 44 0
  3. C. 3 9 44 0
  4. 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

Exams that ask this topic