Find the Derangement of An Array - Problem

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 109 + 7.

Input & Output

Example 1 — Small Case
$ Input: n = 3
Output: 2
💡 Note: Original array [1,2,3] has 2 derangements: [2,3,1] and [3,1,2]. In both cases, no element appears in its original position.
Example 2 — Base Case
$ Input: n = 1
Output: 0
💡 Note: With only one element [1], it's impossible to create a derangement since the element must go somewhere, and the only position is its original position.
Example 3 — Larger Case
$ Input: n = 4
Output: 9
💡 Note: For array [1,2,3,4], there are 9 valid derangements where no element is in its original position. Using formula: D(4) = 3 × (D(3) + D(2)) = 3 × (2 + 1) = 9

Constraints

  • 1 ≤ n ≤ 1000

Visualization

Tap to expand
Derangement of An Array INPUT Original Array [1, 2, 3] 1 pos 1 2 pos 2 3 pos 3 Derangement Rule: No element in its original position Valid Derangements: 2 3 1 [2,3,1] 3 1 2 [3,1,2] n = 3 ALGORITHM STEPS 1 Base Cases D(1)=0, D(2)=1 2 Recurrence Formula D(n) = (n-1) * (D(n-1) + D(n-2)) 3 Apply DP Build solution iteratively 4 Return D(n) mod 10^9+7 Handle large numbers DP Table Calculation: n D(n) Calculation 1 0 base case 2 1 base case 3 2 2*(1+0)=2 FINAL RESULT Number of Derangements 2 Verification: [2, 3, 1] - OK 2!=1, 3!=2, 1!=3 [3, 1, 2] - OK 3!=1, 1!=2, 2!=3 Output: 2 Key Insight: The recurrence D(n) = (n-1) * (D(n-1) + D(n-2)) counts two scenarios for placing element at position 1: 1) Element i goes to position 1 and element 1 goes to position i (swap) -- contributes (n-1)*D(n-2) 2) Element i goes to position 1 but element 1 doesn't go to position i -- contributes (n-1)*D(n-1) TutorialsPoint - Find the Derangement of An Array | Optimal Solution (Dynamic Programming)
Asked in
Google 25 Microsoft 18 Facebook 12
23.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen