Find the Derangement of An Array in C++



Suppose we have an array consisting of n numbers from 1 to n in increasing order, we have to find the number of derangements it can generate.

We know that in combinatorial mathematics, a derangement is a permutation of the elements of a set, such that no element will appear in its original position. The answer may be very large, so return the output mod 10^9 + 7.

So, if the input is like 3, then the output will be 2, as the original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].

To solve this, we will follow these steps −

  • m := 10^9 + 7

  • Define a function add(), this will take a, b,

  • return ((a mod m) + (b mod m)) mod m

  • Define a function mul(), this will take a, b,

  • return ((a mod m) * (b mod m)) mod m

  • From the main method do the following

  • ret := 0

  • if n is same as 1, then −

    • return 0

  • if n is same as 2, then −

    • return 1

  • Define an array dp of size (n + 1)

  • dp[2] := 1

  • for initialize i := 3, when i <= n, update (increase i by 1), do −

    • dp[i] := mul(i - 1, add(dp[i - 2], dp[i - 1]))

  • return dp[n]

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h> using namespace std; typedef long long int lli; const lli m = 1e9 + 7; lli add(lli a, lli b){    return ((a % m) + (b % m)) % m; } lli mul(lli a, lli b){    return ((a % m) * (b % m)) % m; } class Solution { public:    int findDerangement(int n) {       int ret = 0;       if (n == 1)          return 0;       if (n == 2)          return 1;       vector dp(n + 1);       dp[2] = 1;       for (int i = 3; i <= n; i++) {          dp[i] = mul(i - 1, add(dp[i - 2], dp[i - 1]));       }       return dp[n];    } }; main(){    Solution ob;    cout<<(ob.findDerangement(3)); }

Input

3

Output

2
Updated on: 2020-11-16T14:29:44+05:30

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements