Distinct Subsequences II Problem
Description
LeetCode Problem 940.
Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 10^9 + 7.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not.
Example 1:
Input: s = "abc"
Output: 7
Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".
Example 2:
Input: s = "aba"
Output: 6
Explanation: The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba".
Example 3:
Input: s = "aaa"
Output: 3
Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".
Constraints:
- 1 <= s.length <= 2000
- s consists of lowercase English letters.
Solution
Approach: Count Subsequences by Their Last Letter
Listing subsequences is exponential, and counting with a plain "double the total at each step" overcounts as soon as letters repeat. The fix is to group the distinct subsequences by the letter they end with.
Let ends_with[c] be the number of distinct non-empty subsequences seen so far that end with letter c. When we read a letter c, every distinct subsequence that ends with c can be built in exactly one way from what came before:
- append
cto one of the distinct subsequences found so far (there aresum(ends_with)of them), or - take
con its own (+1).
So we set ends_with[c] = sum(ends_with) + 1.
The key detail is that this replaces the old value instead of adding to it. Every subsequence that ended with c before is produced again by this rule (an earlier c can be swapped for the new one), so adding would count it twice. The other letters' counts do not change, because the new c cannot be the last letter of a subsequence ending in another letter.
For s = "aba": after a, ends_with = {a: 1}; after b, {a: 1, b: 2} (b, ab); after the second a, a becomes 1 + 2 + 1 = 4 (a, aa, ba, aba). The answer is 4 + 2 = 6.
The answer is the sum of all 26 counts, taken modulo 109 + 7 throughout.
Complexity: O(26 · n) time, where n is the length of s, and O(1) extra space (26 counters).
class Solution:
def distinctSubseqII(self, s: str) -> int:
MOD = 10**9 + 7
# ends_with[c] = number of distinct non-empty subsequences that end with letter c
ends_with = [0] * 26
for ch in s:
c = ord(ch) - ord("a")
# Append ch to every distinct subsequence so far, or take ch alone (the +1).
# This replaces the old count: those subsequences are all produced again.
ends_with[c] = (sum(ends_with) + 1) % MOD
return sum(ends_with) % MOD
Now write it from memory
Close the write-up and solve it yourself against the tests.