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 with Maximum Beauty INPUT String s = "abbbdd" a b b b d d Frequency f(c): Char Count a 1 b 3 d 2 k = 2 Need 2-char subsequence with unique characters ALGORITHM STEPS 1 Count Frequencies Build freq map: a=1, b=3, d=2 2 Sort by Frequency Descending: b(3), d(2), a(1) b f=3 d f=2 a=1 3 Greedy Selection Pick top k=2 unique chars for max beauty 4 Count Combinations Best: {b, d} with beauty = f(b) + f(d) = 3 + 2 = 5 Max Beauty = 5 Only 1 way to achieve this FINAL RESULT Valid k-subsequences (k=2): {a, b}: beauty = 1+3 = 4 {a, d}: beauty = 1+2 = 3 {b, d}: beauty = 3+2 = 5 MAX Answer 1 Only ONE subsequence achieves maximum beauty {b, d} with beauty = 5 OK - Verified! Key Insight: Greedy approach: To maximize beauty, select k characters with highest frequencies. Use combinatorics C(n,r) when multiple characters share the same frequency at the boundary. TutorialsPoint - Count K-Subsequences of a String With Maximum Beauty | Greedy with Combinatorics
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