Skip to content

Commit 461c6b2

Browse files
committedJun 21, 2025
Add solution #634
1 parent c1384c6 commit 461c6b2

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,7 @@
589589
631|[Design Excel Sum Formula](./solutions/0631-design-excel-sum-formula.js)|Hard|
590590
632|[Smallest Range Covering Elements from K Lists](./solutions/0632-smallest-range-covering-elements-from-k-lists.js)|Hard|
591591
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|
592593
636|[Exclusive Time of Functions](./solutions/0636-exclusive-time-of-functions.js)|Medium|
593594
637|[Average of Levels in Binary Tree](./solutions/0637-average-of-levels-in-binary-tree.js)|Easy|
594595
638|[Shopping Offers](./solutions/0638-shopping-offers.js)|Medium|
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
};

0 commit comments

Comments
 (0)
Please sign in to comment.