Count the Number of Good Subsequences Problem
Description
LeetCode Problem 2539.
A subsequence of a string is good if it is not empty and the frequency of each one of its characters is the same.
Given a string s, return the number of good subsequences of s. Since the answer may be too large, return it modulo 10^9 + 7.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Example 1:
Input: s = "aabb"
Output: 11
Explanation: The total number of subsequences is 2^4. There are five subsequences which are not good: "aabb", "aabb", "aabb", "aabb", and the empty subsequence. Hence, the number of good subsequences is 2^4-5 = 11.
Example 2:
Input: s = "leet"
Output: 12
Explanation: There are four subsequences which are not good: "leet", "leet", "leet", and the empty subsequence. Hence, the number of good subsequences is 2^4-4 = 12.
Example 3:
Input: s = "abcd"
Output: 15
Explanation: All of the non-empty subsequences are good subsequences. Hence, the number of good subsequences is 2^4-1 = 15.
Constraints:
1 <= s.length <= 10^4sconsists of only lowercase English letters.
Solution
Approach: Counting by Frequency + Combinations
Count how often each letter occurs. A good subsequence uses every chosen letter exactly i times, so fix i from 1 up to the largest letter count.
For a letter that occurs v >= i times, there are C(v, i) ways to pick its i copies, plus one way to skip the letter, so C(v, i) + 1 options. Multiplying over all letters with v >= i and subtracting 1 (the empty choice) gives the number of good subsequences where each letter is used i times. Add this up over all i.
Precompute factorials and inverse factorials up to 10^4 modulo 10^9 + 7 to get C(v, i) in O(1).
Complexity: O(n + 26 * max frequency) time, which is O(n) with the 26 letters, and O(n) extra space for the factorial tables.
N = 10001
MOD = 10**9 + 7
f = [1] * N
g = [1] * N
for i in range(1, N):
f[i] = f[i - 1] * i % MOD
g[i] = pow(f[i], MOD - 2, MOD)
def comb(n, k):
return f[n] * g[k] * g[n - k] % MOD
class Solution:
def countGoodSubsequences(self, s: str) -> int:
cnt = Counter(s)
ans = 0
for i in range(1, max(cnt.values()) + 1):
x = 1
for v in cnt.values():
if v >= i:
x = x * (comb(v, i) + 1) % MOD
ans = (ans + x - 1) % MOD
return ans