Count the Number of Good Subsequences

Count subsequences where every distinct character appears the same number of times — combinatorial sum over candidate frequency.

Medium
Time O(n * |Σ|) Space O(n)
LeetCode
7 min read
dp combinatorics

Problem#

A good subsequence: every distinct character in it appears the same number of times. Count good subsequences of s (mod 10⁹ + 7).

Examples#

  • "aabb"11

Constraints#

  • 1 <= s.length <= 10^4.

Approach#

Count frequencies. For each candidate per-character count k = 1..maxFreq, the number of subsequences where every present character appears exactly k times is Π (C(freq[c], k) + 1) - 1 (each char contributes “absent or k copies”, minus the all-absent option). Sum over k.

Solution#

Count Good Subsequences
class Solution {
public:
int countGoodSubsequences(string s) {
const int MOD = 1'000'000'007;
int cnt[26] = {0};
int maxFreq = 0;
for (char c : s) maxFreq = max(maxFreq, ++cnt[c - 'a']);
int n = s.size();
vector<long long> fact(n + 1, 1), inv(n + 1, 1);
auto pw = [&](long long b, long long e) {
long long r = 1; b %= MOD;
while (e) { if (e & 1) r = r * b % MOD; b = b * b % MOD; e >>= 1; }
return r;
};
for (int i = 1; i <= n; ++i) fact[i] = fact[i - 1] * i % MOD;
inv[n] = pw(fact[n], MOD - 2);
for (int i = n - 1; i >= 0; --i) inv[i] = inv[i + 1] * (i + 1) % MOD;
auto C = [&](int N, int K) -> long long {
if (K < 0 || K > N) return 0;
return fact[N] * inv[K] % MOD * inv[N - K] % MOD;
};
long long ans = 0;
for (int k = 1; k <= maxFreq; ++k) {
long long prod = 1;
for (int c = 0; c < 26; ++c) {
prod = prod * (1 + C(cnt[c], k)) % MOD;
}
ans = (ans + prod - 1 + MOD) % MOD;
}
return (int)ans;
}
};

Editorial#

For a fixed k, each letter independently contributes “0 copies” or “exactly k copies” — that’s 1 + C(freq[c], k) options. Multiplying across letters and subtracting the all-absent option yields good subsequences with target frequency k. Sum over all valid k.

Complexity#

  • Time: O(n + 26 * maxFreq).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.