File tree Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Expand file tree Collapse file tree 2 files changed +33
-0
lines changed Original file line number Diff line number Diff line change 589
589
631|[ Design Excel Sum Formula] ( ./solutions/0631-design-excel-sum-formula.js ) |Hard|
590
590
632|[ Smallest Range Covering Elements from K Lists] ( ./solutions/0632-smallest-range-covering-elements-from-k-lists.js ) |Hard|
591
591
633|[ Sum of Square Numbers] ( ./solutions/0633-sum-of-square-numbers.js ) |Medium|
592
+ 634|[ Find the Derangement of An Array] ( ./solutions/0634-find-the-derangement-of-an-array.js ) |Medium|
592
593
636|[ Exclusive Time of Functions] ( ./solutions/0636-exclusive-time-of-functions.js ) |Medium|
593
594
637|[ Average of Levels in Binary Tree] ( ./solutions/0637-average-of-levels-in-binary-tree.js ) |Easy|
594
595
638|[ Shopping Offers] ( ./solutions/0638-shopping-offers.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 634. Find the Derangement of An Array
3
+ * https://leetcode.com/problems/find-the-derangement-of-an-array/
4
+ * Difficulty: Medium
5
+ *
6
+ * In combinatorial mathematics, a derangement is a permutation of the elements of a set,
7
+ * such that no element appears in its original position.
8
+ *
9
+ * You are given an integer n. There is originally an array consisting of n integers from
10
+ * 1 to n in ascending order, return the number of derangements it can generate. Since the
11
+ * answer may be huge, return it modulo 109 + 7.
12
+ */
13
+
14
+ /**
15
+ * @param {number } n
16
+ * @return {number }
17
+ */
18
+ var findDerangement = function ( n ) {
19
+ const MOD = 1e9 + 7 ;
20
+ if ( n === 1 ) return 0 ;
21
+ if ( n === 2 ) return 1 ;
22
+
23
+ let prev2 = 0 ;
24
+ let prev1 = 1 ;
25
+ for ( let i = 3 ; i <= n ; i ++ ) {
26
+ const current = ( ( i - 1 ) * ( prev1 + prev2 ) ) % MOD ;
27
+ prev2 = prev1 ;
28
+ prev1 = current ;
29
+ }
30
+
31
+ return prev1 ;
32
+ } ;
You can’t perform that action at this time.
0 commit comments