Leetcode #634: Find the Derangement of An Array
In this guide, we solve Leetcode #634 Find the Derangement of An Array in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Math, Dynamic Programming, Combinatorics
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: n = 3
Output: 2
Explanation: The original array is [1,2,3]. The two derangements are [2,3,1] and [3,1,2].
Python Solution
def findDerangement(n: int) -> int:
mod = 10**9 + 7
if n == 1:
return 0
dp0, dp1 = 1, 0
for i in range(2, n + 1):
dp0, dp1 = dp1, (i - 1) * (dp0 + dp1) % mod
return dp1
Complexity
The time complexity is , where is the length of the array. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.