


Given a number ‘N', the task is to find the total number of derangements of a set of ‘N’ elements.
A ‘Derangement’ is a permutation of 'N' elements, such that no element appears in its original position. For example, a derangement of {0, 1, 2, 3} is {2, 3, 1, 0}.
For example, 'N' = 2 , {0, 1} and {1, 0} are the only derangement therefore output will be 1.
Input format :
The first line of input contains an integer 'T' denoting the number of test cases.
The first line of each test case contains an integer 'N', the size of the permutation.
Output format :
For each test case, print the total number of derangements of a set of n elements.
The output of each test case will be printed in a separate line.
Note:
The ‘answer’ could be very large, thus output ‘answer’ % (10 ^ 9 + 7).
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 5
1 <= N <= 5*10^3
Time Limit: 1 sec
2
2
1
1
0
For the first test case, For two elements say {0, 1}, there is only one possible derangement {1, 0}.
For the second test case, For one element say {0}, it is not possible to any derangement because there is only one element and it is always placed in its original position.
2
4
3
9
2
Can you form the recurrence relation?
O(2 ^ N), where N is the number given.
This is because for every state we have two options. Thus, the final time complexity will be O(2 ^ N).
O(N), where N is the number given.
Since we are using recursion, and at the moment recursion stack here can have N items. Thus, the final space complexity will be O(N).