Count Derangements (Permutation such that no element appears in its original position)
Pattern: 1D DP
A derangement moves every element away from its own place. Element n goes to some place j (n - 1 choices); then either j goes to n's place (D(n-2) ways for the rest) or it does not (D(n-1) ways). So D(n) = (n - 1)(D(n-1) + D(n-2)).
The problem
Return the number of permutations of n items where no item stays in its original place. The answer is taken modulo 10⁹ + 7. n = 3 gives 2.
Think first
- Where can item n go?
- After item n goes to place j, where can item j go?
- What are the base cases?
Hints
Brute force, and why it fails
Try every permutation: n!. The tests use this for small n.
The key insight
Splitting on where item j goes gives two smaller derangement counts.
Dry run
| d | 0 1 |
|---|
D(1) = 0, D(2) = 1.
Step 1 of 3
The plan
a, b = D(0) = 1, D(1) = 0
for i in 2..n: a, b = b, (i - 1)(a + b)
Complexity
- Time
O(n)- Space
O(1)
Two values carried.
Edge cases
- n = 1: 0.
- n = 2: 1.
- Large n: modulo.
I've built my logic, show the code
Java
class Solution {
public int countDer(int n) {
final long MOD = 1_000_000_007L;
if (n == 1) return 0;
long a = 1, b = 0; // D(0) = 1, D(1) = 0
for (int i = 2; i <= n; i++) { // element i swaps with some j, or goes to j's place while j moves on
long c = (long) (i - 1) * ((a + b) % MOD) % MOD;
a = b;
b = c;
}
return (int) b;
}
}C++
class Solution {
public:
int countDer(int n) {
const long long MOD = 1000000007LL;
if (n == 1) return 0;
long long a = 1, b = 0; // D(0) = 1, D(1) = 0
for (int i = 2; i <= n; i++) { // element i swaps with some j, or goes to j's place while j moves on
long long c = static_cast<long long>(i - 1) * ((a + b) % MOD) % MOD;
a = b;
b = c;
}
return static_cast<int>(b);
}
};Python
class Solution:
def countDer(self, n: int) -> int:
MOD = 1_000_000_007
a, b = 1, 0 # D(0) = 1, D(1) = 0
for i in range(2, n + 1): # element i swaps with some j, or goes to j's place while j moves on
a, b = b, (i - 1) * (a + b) % MOD
return bCommon mistakes
- Using D(0) = 0.
- Overflow.