Count K-Subsequences of a String With Maximum Beauty - Problem

You are given a string s and an integer k.

A k-subsequence is a subsequence of s, having length k, and all its characters are unique, i.e., every character occurs once.

Let f(c) denote the number of times the character c occurs in s.

The beauty of a k-subsequence is the sum of f(c) for every character c in the k-subsequence.

For example, consider s = "abbbdd" and k = 2:

  • f('a') = 1, f('b') = 3, f('d') = 2
  • Some k-subsequences of s are:
    • "abbbdd" → "ab" having a beauty of f('a') + f('b') = 4
    • "abbbdd" → "ad" having a beauty of f('a') + f('d') = 3
    • "abbbdd" → "bd" having a beauty of f('b') + f('d') = 5

Return an integer denoting the number of k-subsequences whose beauty is the maximum among all k-subsequences. Since the answer may be too large, return it modulo 10^9 + 7.

Note: f(c) is the number of times a character c occurs in s, not a k-subsequence.

Input & Output

Example 1 — Basic Case
$ Input: s = "abbbdd", k = 2
Output: 1
💡 Note: Characters: a(freq=1), b(freq=3), d(freq=2). For k=2, possible combinations are (a,b)→beauty=4, (a,d)→beauty=3, (b,d)→beauty=5. Maximum beauty is 5, achieved by 1 combination.
Example 2 — Multiple Ways
$ Input: s = "aabbcc", k = 2
Output: 3
💡 Note: Each character appears twice. Any 2 characters give beauty=4. There are C(3,2)=3 ways to choose 2 from {a,b,c}.
Example 3 — Edge Case
$ Input: s = "abc", k = 1
Output: 3
💡 Note: Each character appears once. Maximum beauty is 1, achieved by selecting any single character. 3 ways total.

Constraints

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

Visualization

Tap to expand
K-Subsequences Maximum Beauty ProblemInput: s = "abbbdd", k = 2abbbddCharacter frequencies: f(a)=1, f(b)=3, f(d)=2All possible k=2 subsequences with unique characters:(a,b): 1+3=4(a,d): 1+2=3(b,d): 3+2=5Maximum beauty = 5Number of subsequences with maximum beauty = 1Output: 1
Understanding the Visualization
1
Input Analysis
String s with character frequencies and target subsequence length k
2
Beauty Calculation
Beauty = sum of f(c) for each character c in subsequence
3
Count Maximum
Count how many k-subsequences achieve the maximum possible beauty
Key Takeaway
🎯 Key Insight: Greedily select characters with highest frequencies and use combinatorics to count arrangements when frequencies are tied
Asked in
Google 25 Meta 18 Amazon 15
24.0K Views
Medium Frequency
~35 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