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: 6
💡 Note: Good subsequences: "a" (pos 0), "a" (pos 1), "b" (pos 2), "aa" (pos 0,1), "ab" (pos 0,2), "ab" (pos 1,2). All have equal character frequencies within each subsequence.
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 the Number of Good Subsequences INPUT String s = "aab" 'a' 'a' 'b' idx 0 idx 1 idx 2 Character Frequency Char Count 'a' 2 'b' 1 All Subsequences: "a", "a", "b", "aa", "ab", "ab", "aab" (7 non-empty subsequences) ALGORITHM STEPS 1 Count frequencies cnt['a']=2, cnt['b']=1 2 For each freq k (1 to max) Count subseq with all chars k times 3 Use combinations C(n,k) Pick k chars from each type 4 Multiply and subtract 1 (C(n,k)+1) for each char, -1 for empty Calculation for k=1: C(2,1)+1 = 3 (for 'a') C(1,1)+1 = 2 (for 'b') Result = 3 * 2 - 1 = 5 For k=2: C(2,2)+1=2, but b has 1 Only "aa" qualifies = 1 subseq FINAL RESULT Good Subsequences Found: "a" freq(a)=1 [OK] "a" freq(a)=1 [OK] "b" freq(b)=1 [OK] NOT Good: "aab" a:2, b:1 [NO] "ab" a:1, b:1 [OK] Output: 3 "a", "a", "b" Key Insight: A "good" subsequence requires ALL characters to appear the same number of times. Use DP with combinatorics: for each target frequency k, compute ways to pick exactly k occurrences from each character. Multiply choices across all chars, subtract 1 for empty set. TutorialsPoint - Count the Number of Good Subsequences | Dynamic Programming with Memoization
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