Skip to content

Commit 9248ecd

Browse files
committed
Add solution #940
1 parent d938188 commit 9248ecd

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -749,6 +749,7 @@
749749
937|[Reorder Data in Log Files](./solutions/0937-reorder-data-in-log-files.js)|Medium|
750750
938|[Range Sum of BST](./solutions/0938-range-sum-of-bst.js)|Easy|
751751
939|[Minimum Area Rectangle](./solutions/0939-minimum-area-rectangle.js)|Medium|
752+
940|[Distinct Subsequences II](./solutions/0940-distinct-subsequences-ii.js)|Hard|
752753
966|[Vowel Spellchecker](./solutions/0966-vowel-spellchecker.js)|Medium|
753754
970|[Powerful Integers](./solutions/0970-powerful-integers.js)|Easy|
754755
976|[Largest Perimeter Triangle](./solutions/0976-largest-perimeter-triangle.js)|Easy|
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 940. Distinct Subsequences II
3+
* https://leetcode.com/problems/distinct-subsequences-ii/
4+
* Difficulty: Hard
5+
*
6+
* Given a string s, return the number of distinct non-empty subsequences of s. Since the answer
7+
* may be very large, return it modulo 109 + 7.
8+
*
9+
* A subsequence of a string is a new string that is formed from the original string by deleting
10+
* some (can be none) of the characters without disturbing the relative positions of the remaining
11+
* characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not.
12+
*/
13+
14+
/**
15+
* @param {string} s
16+
* @return {number}
17+
*/
18+
var distinctSubseqII = function(s) {
19+
const MOD = 1e9 + 7;
20+
const lastOccurrence = new Array(26).fill(-1);
21+
const dp = new Array(s.length + 1).fill(0);
22+
dp[0] = 1;
23+
24+
for (let i = 0; i < s.length; i++) {
25+
const charIndex = s.charCodeAt(i) - 97;
26+
dp[i + 1] = (dp[i] * 2) % MOD;
27+
if (lastOccurrence[charIndex] !== -1) {
28+
dp[i + 1] = (dp[i + 1] - dp[lastOccurrence[charIndex]] + MOD) % MOD;
29+
}
30+
lastOccurrence[charIndex] = i;
31+
}
32+
33+
return (dp[s.length] - 1 + MOD) % MOD;
34+
};

0 commit comments

Comments
 (0)