Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

634. Find the Derangement of An Array

Explanation

To find the derangement of an array, we need to find a permutation of the array where no element appears in its original position. This can be solved using dynamic programming. We can define the derangement of an array of size n as the number of ways to rearrange the elements such that no element appears in its original position.

We can use the principle of inclusion-exclusion to compute the derangement for each element. Let dp[i] represent the number of derangements for an array of size i.

The recursive formula for computing dp[i] is:

dp[i] = (i-1) * (dp[i-1] + dp[i-2])
class Solution {
    public int findDerangement(int n) {
        if (n <= 1) {
            return 0;
        }
        long dp1 = 0, dp2 = 1;
        for (int i = 3; i <= n; i++) {
            long dp = (i - 1) * (dp1 + dp2) % 1000000007;
            dp1 = dp2;
            dp2 = dp;
        }
        return (int)dp2;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.