> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Find the Derangement of An Array

> Tested Python solution for LeetCode 634 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 634, [Medium](/catalog/medium). Topics: [Math](/catalog/topics/math), [Dynamic Programming](/catalog/topics/dynamic-programming), Combinatorics. [View on LeetCode](https://leetcode.com/problems/find-the-derangement-of-an-array/description/).

Generate this problem as a practice environment: tested reference solution, 12 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 634   # by problem number
lcpy gen -s find_the_derangement_of_an_array   # by problem name
```

## Problem

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** `10^9 + 7`.

### Examples

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

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

### Constraints

* `1 <= n <= 10^6`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_the_derangement_of_an_array/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/find_the_derangement_of_an_array/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def find_derangement(self, n: int) -> int:
        mod = 1_000_000_007
        if n == 1:
            return 0
        a, b = 1, 0  # D(1) = 0 carried via a = D(k-1)
        for k in range(2, n + 1):
            a, b = b, (k - 1) * (a + b) % mod
        return b % mod
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.