> For the complete documentation index, see [llms.txt](https://jaywin.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jaywin.gitbook.io/leetcode/solutions/0634-find-the-derangement-of-an-array.md).

# 0634. Find the Derangement of An Array

<https://leetcode.com/problems/find-the-derangement-of-an-array>

## Description

In combinatorial mathematics, a **derangement** is a permutation of the elements of a set, such that no element appears in its original position.

You are given an integer `n`. There is originally an array consisting of `n` integers from `1` to `n` in ascending order, return *the number of **derangements** it can generate*. Since the answer may be huge, return it **modulo** `109 + 7`.

**Example 1:**

```
**Input:** n = 3
**Output:** 2
**Explanation:** The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].
```

**Example 2:**

```
**Input:** n = 2
**Output:** 1
```

**Constraints:**

* `1 <= n <= 106`

## ac

```java
class Solution {
    public int findDerangement(int n) {
        int mod = 1000000007;
        long[] dp = new long[n+1];
        dp[0] = 1;
        for (int i = 2; i < dp.length; i++) {
            dp[i] = ((i - 1) * ((dp[i-2] + dp[i-1]) % mod)) % mod;
        }
        return (int)dp[n];
    }
}

/*
for i, it has 2 option: 1) j-th take i-value, i take j-value, then we have dp[n-1] possible; 2) j-th take i-value, i dont' take j-value, we have dp[n-1] possible; 3) we have (i-1) j-th position, so dp[i] = (i-1) * (dp[i-1] + dp[i-2]);
*/
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jaywin.gitbook.io/leetcode/solutions/0634-find-the-derangement-of-an-array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
