LeetCode 2539. Count the Number of Good Subsequences Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
2539. Count the Number of Good Subsequences

Description

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 109 + 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 24. There are five subsequences which are not good: "aabb", "aabb", "aabb", "aabb", and the empty subsequence. Hence, the number of good subsequences is 24-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 24-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 24-1 = 15.

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of only lowercase English letters.

Solutions

Solution 1

PythonJavaC++Go
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !