Find the Derangement of An Array Problem
Description
LeetCode Problem 634.
In combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element appears in its original position.
You are given an integer n. There is originally an array consisting of n integers from 1 to n in ascending order, return the number of derangements it can generate. Since the answer may be huge, return it modulo 10^9 + 7.
Example 1:
Input: n = 3
Output: 2
Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].
Example 2:
Input: n = 2
Output: 1
Constraints:
1 <= n <= 10^6
Solution
Approach: Dynamic Programming on the Count
Let f[i] be the number of derangements of i elements. Build it up from smaller sizes by asking where element 1 goes.
Element 1 cannot stay in position 1, so it goes to some position j, one of i - 1 choices. Now look at element j, whose own position has been taken:
- Element
jgoes to position1. Then1andjhave simply swapped, and the otheri - 2elements must be deranged among themselves:f[i - 2]ways. - Element
jdoes not go to position1. Then position1plays the role ofj's forbidden spot. We are deranging thei - 1elements other than1over thei - 1positions other thanj, each with exactly one forbidden position:f[i - 1]ways.
So f[i] = (i - 1) * (f[i - 1] + f[i - 2]), starting from f[0] = 1 (the empty arrangement) and f[1] = 0 (a single element always stays put). For n = 3 this gives 2 * (0 + 1) = 2, as in example 1.
Each value only needs the previous two, so two variables are enough. Take every value modulo 10^9 + 7; the product (i - 1) * (f[i - 1] + f[i - 2]) can reach about 2 * 1015, so compute it in a 64-bit integer (in JavaScript it still fits exactly in a double).
Complexity: O(n) time and O(1) extra space.
class Solution:
def findDerangement(self, n: int) -> int:
mod = 10**9 + 7
prev, cur = 1, 0 # derangements of 0 and of 1 element
for i in range(2, n + 1):
prev, cur = cur, (i - 1) * (prev + cur) % mod
return cur