Skip to main content
LeetCode 634, Medium. Topics: Math, Dynamic Programming, Combinatorics. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 12 parametrized pytest cases, and a playground notebook:

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

Constraints

  • 1 <= n <= 10^6

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026