Count the Number of Good Subsequences - Problem

A good subsequence is a fascinating string pattern where every character appears the same number of times! ๐ŸŽฏ

Given a string s, you need to count how many non-empty subsequences have this special property where all characters have equal frequency. For example, in "abc", the subsequence "abc" is good because each character appears exactly once.

Remember: A subsequence maintains the original order but can skip characters. Since the result can be huge, return it modulo 109 + 7.

Example: For s = "aab", good subsequences include "a" (appears twice), "b", and "ab" (both characters appear once).

Input & Output

example_1.py โ€” Simple case
$ Input: s = "aab"
โ€บ Output: 6
๐Ÿ’ก Note: Good subsequences: "a" (2 ways), "b" (1 way), "aa" (1 way), "ab" (2 ways). Total = 6 subsequences where all characters have equal frequency.
example_2.py โ€” All same characters
$ Input: s = "aaa"
โ€บ Output: 7
๐Ÿ’ก Note: Good subsequences: "a" (3 ways), "aa" (3 ways), "aaa" (1 way). Total = 7 subsequences.
example_3.py โ€” All different characters
$ Input: s = "abc"
โ€บ Output: 7
๐Ÿ’ก Note: Good subsequences: single chars "a", "b", "c" (3 ways), pairs "ab", "ac", "bc" (3 ways), triple "abc" (1 way). Total = 7.

Constraints

  • 1 โ‰ค s.length โ‰ค 104
  • s consists of lowercase English letters only
  • Return result modulo 109 + 7

Visualization

Tap to expand
๐ŸŽผ The Smart Conductor's Method๐ŸŽป A2 violins๐ŸŽน B1 pianoGroup Size k=1:Ways to pick 1 violin: C(2,1) = 2Ways to pick 1 piano: C(1,1) = 1Total: 2 ร— 1 = 2Single Musicians:Individual violinists: 2 waysIndividual pianist: 1 wayTotal: 2 + 1 = 3๐ŸŽฏ Result: 2 + 3 + 1 = 6 balanced performances!No need to check each combination individually!
Understanding the Visualization
1
Count Musicians
Count how many of each instrument type are available
2
Plan Group Sizes
For each possible group size k, check if we have enough of each instrument
3
Calculate Combinations
Use C(n,k) to count ways to select k musicians from n available of each type
4
Multiply Results
Multiply combinations across all instrument types to get total arrangements
Key Takeaway
๐ŸŽฏ Key Insight: Instead of generating all subsequences, we use combinatorial mathematics to count them directly by calculating C(frequency, target) for each character and multiplying the results.
Asked in
Google 35 Microsoft 28 Amazon 22 Meta 15
28.4K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen