Taro Logo

Find the Derangement of An Array

Medium
Asked by:
IXL
0 views
Topics:
Dynamic Programming

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the upper bound for $n$, and do we need to worry about integer overflow before applying the modulo operation?
  2. How should we handle extreme edge cases where $n = 0$ or $n = 1$, and is $n$ guaranteed to be a non-negative integer?
  3. Could you clarify the definition of the elements in the sequence—are they strictly the integers from $1$ to $n$, or could the input be an arbitrary array of $n$ distinct elements?
  4. Since we need to return the answer modulo $10^9 + 7$, should intermediate calculations also be modulo-arithmetic to prevent overflow?
  5. Are we only required to return the *count* of total derangements, or do we also need to generate and return the actual permutations themselves?

Brute Force Solution

Approach

This problem asks for the number of derangements of a set of size n, which counts permutations where no element remains in its original position. We can compute this using the well-known recurrence relation where the count for n depends on the counts for n minus one and n minus two. By tracking only the last two computed values and applying modulo arithmetic at each step, we achieve an efficient solution.

Here's how the algorithm would work step-by-step:

  1. Define the modulo constant as ten to the power of nine plus seven.
  2. Check the base case where the input size is one or less, returning zero since no valid derangement exists.
  3. Initialize two variables to store the base derangement counts for inputs one and two.
  4. Iterate from three up to the given number of elements, calculating the current derangement using the recurrence formula.
  5. Update the stored counts for the next iteration while keeping the results within the modulo bound.
  6. Return the final derangement count after completing the loop.

Code Implementation

def find_derangement(number_of_elements):
    modulo_value = 10**9 + 7
    # Return zero immediately when there is only one element
    if number_of_elements <= 1:
        return 0
    # Initialize base derangement counts for n equal to 1 and 2
    previous_two = 0
    previous_one = 1
    # Compute subsequent derangements iteratively using constant space
    for current_index in range(3, number_of_elements + 1):
        current_derangement = ((current_index - 1) * (previous_one + previous_two)) % modulo_value
        previous_two = previous_one
        previous_one = current_derangement
    return previous_one

Big(O) Analysis

Time Complexity
O(n) – The solution uses a single loop that runs from 3 up to n, performing constant-time arithmetic operations at each step.
Space Complexity
O(1) – Only a few scalar variables are used to maintain the previous two derangement counts, requiring constant additional memory.

Optimal Solution

Approach

A derangement is a permutation where none of the elements appear in their original positions. The number of derangements follows a well-known recurrence relation: D(n) = (n - 1) * (D(n - 1) + D(n - 2)). By maintaining only the last two results, the result can be computed iteratively in linear time and constant extra space.

Here's how the algorithm would work step-by-step:

  1. Check if the input size is less than or equal to 1, returning 0 immediately.
  2. Set the modulus to 10^9 + 7 to prevent integer overflow and keep calculations bounded.
  3. Initialize two variables to represent derangements for n = 1 (which is 0) and n = 2 (which is 1).
  4. Iterate from 3 up to n, applying the formula (i - 1) * (prev1 + prev2) modulo 10^9 + 7.
  5. Update the two tracking variables at each step to roll forward.
  6. Return the final derangement value for size n.

Code Implementation

def find_derangement(number_of_elements: int) -> int:
    if number_of_elements <= 1:
        return 0
    modulo = 1_000_000_007
    # Initialize base values for derangements of size 1 and size 2
    previous_two = 0
    previous_one = 1
    # Iteratively compute derangements from size 3 up to the target size
    for current_size in range(3, number_of_elements + 1):
        # Apply the standard recurrence relation for derangements
        current_value = ((current_size - 1) * (previous_one + previous_two)) % modulo
        previous_two = previous_one
        previous_one = current_value
    # Return the computed count for the requested number of elements
    return previous_one

Big(O) Analysis

Time Complexity
O(n) – The algorithm computes the derangement count using a single loop that runs from 3 up to n, executing a constant number of arithmetic operations per iteration.
Space Complexity
O(1) – Only a few scalar variables are used to store the running counts and the modulo constant, requiring constant auxiliary space.

Edge Cases

Input n equals 1 representing a single element
How to Handle:
The recurrence relation or base case must immediately return 0 since a single element cannot be deranged.
Input n equals 2 representing two elements
How to Handle:
The base case must correctly return 1 because the only permutation swaps the two elements.
Maximum allowed inputs up to one hundred thousand
How to Handle:
The solution must use dynamic programming with O(n) time and space complexity to prevent Time Limit Exceeded or memory limits.
Large intermediate integer addition causing overflow
How to Handle:
We apply modulo 10 to the power of 9 plus 7 at every addition step to keep values within standard integer bounds.
Input n is zero or negative
How to Handle:
The function should include a validation check at the beginning to return 0 or throw an invalid argument exception.
Deep recursion causing stack overflow if implemented recursively
How to Handle:
An iterative bottom up dynamic programming approach avoids call stack limits entirely.