Topics

A derangement is a permutation with no fixed points. We can derive a recurrence as follows:

  • Consider the derangement direct formula, i.e. :
  • Multiply by :
  • Adding to both sides:
  • Notice that:
  • Simplifying the right-hand side:
  • Therefore, we have:

Below code is what’s preferred to use in competitive programming

int derangement_recursive(int n, long long mod) {
    if (n == 0) {
        return 1; // base case
    }
    long long c = derangement(n - 1, mod);
    c = n * c + (n % 2 == 1 ? -1 : 1);
    return (c + mod)%mod;
}
 
int derangement_iterative(int n, long long mod) {
    long long c = 1; // base case
    for (int i = 1; i <= n; ++i){
        c = (c * i) + (i % 2 == 1 ? -1 : 1);
        c = (c + mod)%mod; // +mod to handle neg vals as well
    }
    return c;
}