-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0940-distinct-subsequences-ii.js
More file actions
38 lines (32 loc) · 1.06 KB
/
0940-distinct-subsequences-ii.js
File metadata and controls
38 lines (32 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Distinct Subsequences II
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var distinctSubseqII = function (s) {
const moduloValue = 1e9 + 7;
const subsequenceCounts = new Array(s.length + 1).fill(0);
subsequenceCounts[0] = 1;
const lastSeenPosition = new Array(26).fill(-1);
for (
let currentCharacterIndex = 0;
currentCharacterIndex < s.length;
currentCharacterIndex++
) {
const alphabetMapping = s.charCodeAt(currentCharacterIndex) - 97;
let currentSubsequenceTotal =
(subsequenceCounts[currentCharacterIndex] * 2) % moduloValue;
if (lastSeenPosition[alphabetMapping] !== -1) {
currentSubsequenceTotal =
(currentSubsequenceTotal -
subsequenceCounts[lastSeenPosition[alphabetMapping]] +
moduloValue) %
moduloValue;
}
subsequenceCounts[currentCharacterIndex + 1] = currentSubsequenceTotal;
lastSeenPosition[alphabetMapping] = currentCharacterIndex;
}
const resultNonEmpty =
(subsequenceCounts[s.length] - 1 + moduloValue) % moduloValue;
return resultNonEmpty;
};