Problem · Dynamic Programming

Count Array Derangements

Learn this problem
MediumInMobi logoInMobiFULLTIMEPHONE SCREEN

Problem statement

A derangement is a permutation in which no element remains in its original position.

You are given an integer n. Start with the array [1, 2, ..., n] in ascending order. Return the number of distinct derangements of this array.

Because the answer can be large, return it modulo 10^9 + 7.

Function

findDerangement(n: int) → int

Examples

Example 1

n = 3return = 2

The two derangements are [2, 3, 1] and [3, 1, 2].

Example 2

n = 2return = 1

The only derangement is [2, 1].

Constraints

  • 1 ≤ n ≤ 10^6

More InMobi problems

drafts saved locally
public int findDerangement(int n) {
  // write your code here
}
n3
expected2
checking account