GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

Ask a Question


Start Coding Today




Data Structures


Interview Experiences

C Programming

C++ Programming

Java Programming



Find total permutation of the elements of a set, such that no element appears in its original position.

A number N will be given to you,  you need to tell total number of permutation ?

asked Nov 16, 2015 by no3

1 Answer

This problem is popularly known as derangement problem.

The explanation is given below -  
Suppose that there are n persons numbered 1, 2, ..., n. Let there be n hats also numbered 1, 2, ..., n. We have to find the number of ways in which no one gets the hat having same number as his/her number. 
Let us assume that the first person takes hat i. There are n - 1 ways for the first person to make such a choice. There are now two possibilities, depending on whether or not person i takes hat 1.

In this way you can derive  a recurrence relation for same.

Read more about that at -

Now you can write code as below - 

#include <bits/stdc++.h>
using namespace std;

int main()
    int N;
    cin >> N;
    int der[N + 1];
    der[0] = 1;
    der[1] = 0;
    der[2] = 1;

    for (int i = 3; i <= N; ++i)
        der[i] = (i - 1)*(der[i - 1] + der[i - 2]);
    cout << der[N] << endl;



answered Nov 16, 2015 by utkarsh111