Count derangements
A Derangement is a permutation of ‘N’ elements, such that no element appears in its original position. For example, an instance of derangement of {0, 1, 2, 3} is {2, 3, 1, 0}, because 2 present at index 0 is not at its initial position which is 2 and similarly for other elements of the sequence.
Given a number ‘N’, find the total number of derangements possible of a set of 'N’ elements.
Note:
The answer could be very large, output answer %(10 ^ 9 + 7).
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line and the only line of each test case contains an integer ‘N’ denoting the number of elements whose derangements are to be counted.
Output Format:
For each test case, return the total number of derangements of a set of ‘N’ elements.
Note:
You don't need to print anything, it has been already taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 3000
Time limit: 1 sec
CodingNinjas
author
2y
Step 1 I followed the recursive approach initially, even though it passed all the cases.
Step 2 I still had time so changed it to DP, which reduced my time.
CodingNinjas
author
2y
Recursive approach.
Let’s understand this approach with an example.
Consider ‘N’ = 4, the elements will be {0, 1, 2 ,3}.
- The element 0 can be placed at any index except 0 because the element cannot be ...read more
CodingNinjas
author
2y
Bottom-up approach
We can observe that this implementation, recalculates various problems. So, to avoid this, the idea is to store the results of subproblems in an array and build the array in a bottom...read more
CodingNinjas
author
2y
Optimised approach
The steps are as follows:
- In the bottom-up approach, extra space is used to store subproblems. However, we only need two previous values to calculate the count of derangements of the...read more
Add answer anonymously...
Top Nagarro Technical Trainee interview questions & answers
Popular interview questions of Technical Trainee
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app