Count the Number of Good Subsequences - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "aab"
Output: 3
💡 Note: Good subsequences: "a" (frequency: a=1), "aa" (frequency: a=2), "b" (frequency: b=1). All have equal character frequencies.
Example 2 — Single Character
$ Input: s = "aaaa"
Output: 4
💡 Note: Good subsequences: "a", "aa", "aaa", "aaaa". Each has only character 'a' with frequencies 1, 2, 3, 4 respectively.
Example 3 — Mixed Characters
$ Input: s = "abc"
Output: 3
💡 Note: Good subsequences: "a", "b", "c". Each single character has frequency 1. "ab", "ac", "bc", "abc" are not good because they have different character frequencies.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters only

Visualization

Tap to expand
Count Good Subsequences: "aab" → 3"aab"Input String"a""aa""b"freq=1freq=2freq=1"ab" ✗"aab" ✗"bb" ✗Good SubsequencesBad SubsequencesCount: 3All chars same freqGood: All characters have equal frequencyBad: Characters have different frequenciesOutput: 3
Understanding the Visualization
1
Input String
Given string with characters to analyze
2
Find Good Subsequences
Identify subsequences where all characters have same frequency
3
Count Result
Return total count modulo 10^9 + 7
Key Takeaway
🎯 Key Insight: Use combinatorics to count subsequences with equal character frequencies instead of generating them all
Asked in
Google 25 Microsoft 20 Amazon 15
12.5K Views
Medium Frequency
~35 min Avg. Time
234 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