This is a premium problem. We're working on making it available for free soon.
Explore Free ProblemsSolutions for this premium problem will be available for free soon.
Browse Free ProblemsWatch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
The recurrence works by analyzing where the first element can move among the remaining positions. Once placed, the rest of the elements either swap with it or form derangements among themselves, leading to the formula D(n) = (n - 1) * (D(n - 1) + D(n - 2)).
Variations of derangement and permutation counting problems do appear in technical interviews, especially those involving combinatorics and dynamic programming. Understanding the recurrence and DP optimization is useful for many interview scenarios.
A simple dynamic programming array is commonly used to store intermediate derangement counts. However, since each value only depends on the previous two, the solution can be optimized to constant space using two variables.
The optimal approach uses a mathematical recurrence with dynamic programming. The number of derangements follows D(n) = (n - 1) * (D(n - 1) + D(n - 2)), which can be computed iteratively. This avoids generating permutations and runs in linear time.