Problem · Dynamic Programming
Count Array Derangements
Learn this problemProblem statement
A derangement is a permutation in which no element remains in its original position.
You are given an integer n. Start with the array [1, 2, ..., n] in ascending order. Return the number of distinct derangements of this array.
Because the answer can be large, return it modulo 10^9 + 7.
Function
findDerangement(n: int) → intExamples
Example 1
n = 3return = 2The two derangements are [2, 3, 1] and [3, 1, 2].
Example 2
n = 2return = 1The only derangement is [2, 1].
Constraints
1 ≤ n ≤ 10^6