Find the Derangement of An Array - Problem
Derangement Problem: The Perfect Shuffle Challenge

In combinatorial mathematics, a derangement is a fascinating permutation where every element is displaced from its original position. Think of it as the "perfect shuffle" where nothing ends up where it started!

๐ŸŽฏ Your Mission: Given an integer n, calculate how many derangements are possible for an array containing integers from 1 to n in ascending order.

๐Ÿ“Š Example: For n = 3 with array [1, 2, 3]:
โ€ข Valid derangement: [2, 3, 1] โœ… (no element at original position)
โ€ข Invalid: [1, 3, 2] โŒ (element 1 is still at position 0)

โš ๏ธ Important: Since the result can be astronomically large, return the answer modulo 109 + 7.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 3
โ€บ Output: 2
๐Ÿ’ก Note: For array [1,2,3], the valid derangements are [2,3,1] and [3,1,2]. In both cases, no element appears at its original position.
example_2.py โ€” Edge Case
$ Input: n = 1
โ€บ Output: 0
๐Ÿ’ก Note: With only one element [1], it's impossible to create a derangement since the element must stay in its original position.
example_3.py โ€” Larger Case
$ Input: n = 4
โ€บ Output: 9
๐Ÿ’ก Note: For array [1,2,3,4], there are 9 valid derangements out of 24 total permutations. The derangements ensure no element i is at position i.

Visualization

Tap to expand
๐ŸŽฉ The Hat Check ProblemGuest 1Guest 2Guest 3Hat 1Hat 2Hat 3Valid Derangements:Arrangement 1: [Hat2, Hat3, Hat1] โœ…Arrangement 2: [Hat3, Hat1, Hat2] โœ…Derangement FormulaD(n) = (n-1) ร— [D(n-1) + D(n-2)]Base cases:D(1) = 0, D(2) = 1For n=3: D(3) = 2ร—(1+0) = 2
Understanding the Visualization
1
Setup
n guests check their hats numbered 1 to n
2
Constraint
No guest can receive their own hat back
3
Count
How many ways can we return all hats incorrectly?
4
Formula
D(n) = (n-1) ร— [D(n-1) + D(n-2)]
Key Takeaway
๐ŸŽฏ Key Insight: The derangement formula elegantly captures the combinatorial structure: choose any of (n-1) positions for the first element, then either create a swap or recursively solve smaller subproblems.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through n iterations

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only storing previous two values

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 106
  • Return result modulo 109 + 7
  • Time limit: 1 second
Asked in
Google 25 Amazon 15 Microsoft 12 Bloomberg 8
28.5K Views
Medium Frequency
~15 min Avg. Time
856 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