Skip to main content

Count K-Subsequences of a String With Maximum Beauty - Solution & Explanation

HardHash TableMathStringGreedy19 min readAsked at: Google
Practice this problem

Problem Statement

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 109 + 7.

A subsequence of a string is a new string formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.

Notes

  • f(c) is the number of times a character c occurs in s, not a k-subsequence.
  • Two k-subsequences are considered different if one is formed by an index that is not present in the other. So, two k-subsequences may form the same string.

 

Example 1:

Input: s = "bcca", k = 2
Output: 4
Explanation: From s we have f('a') = 1, f('b') = 1, and f('c') = 2.
The k-subsequences of s are: 
bcca having a beauty of f('b') + f('c') = 3 
bcca having a beauty of f('b') + f('c') = 3 
bcca having a beauty of f('b') + f('a') = 2 
bcca having a beauty of f('c') + f('a') = 3
bcca having a beauty of f('c') + f('a') = 3 
There are 4 k-subsequences that have the maximum beauty, 3. 
Hence, the answer is 4. 

Example 2:

Input: s = "abbcd", k = 4
Output: 2
Explanation: From s we have f('a') = 1, f('b') = 2, f('c') = 1, and f('d') = 1. 
The k-subsequences of s are: 
abbcd having a beauty of f('a') + f('b') + f('c') + f('d') = 5
abbcd having a beauty of f('a') + f('b') + f('c') + f('d') = 5 
There are 2 k-subsequences that have the maximum beauty, 5. 
Hence, the answer is 2. 

 

Constraints:

  • 1 <= s.length <= 2 * 105
  • 1 <= k <= s.length
  • s consists only of lowercase English letters.

Approach Overview

Problem Overview: Given a string s and integer k, count the number of distinct k-subsequences that achieve the maximum possible beauty. Beauty is defined as the sum of frequencies of the chosen characters in the original string. The challenge is selecting the best k distinct characters and counting how many subsequences can be formed.

Approach 1: Greedy with Frequency Count (O(n + m log m) time, O(m) space)

Start by counting character frequencies using a hash table. Sort the frequencies in descending order and select the top k characters to maximize beauty. The number of valid subsequences equals the product of the frequencies of the chosen characters. When multiple characters share the same frequency at the boundary, combinations are required to count how many ways you can pick them. This approach relies on a simple greedy rule: always prioritize characters with the highest frequency.

Approach 2: Mathematical Combinatorics (O(n + m log m) time, O(m) space)

After computing frequencies, sort them and determine the cutoff frequency for the k-th character. All characters with higher frequency must be chosen. For characters with the same cutoff frequency, compute how many need to be selected and apply combinatorial math C(n, r). Multiply this by the frequency contributions to count subsequences. This approach leverages combinatorics to efficiently handle ties without enumerating subsets.

Approach 3: Greedy with Frequency Counting (Optimized) (O(n + m log m) time, O(m) space)

Count frequencies and store them in an array. Sort descending and iterate through the largest values while tracking how many characters are used. If a frequency group exceeds the remaining slots, compute combinations only for that group. Multiplying contributions with modular arithmetic avoids overflow. The greedy decision works because maximizing beauty always means choosing the highest-frequency characters first.

Approach 4: Combinatorial Selection with Frequency Groups (O(n + m log m) time, O(m) space)

Group characters by frequency and process them from highest to lowest. Maintain remaining selections and accumulate subsequence counts using combinatorial selection. Instead of treating characters individually, operate on frequency groups, which simplifies tie handling and reduces repeated calculations. The logic combines greedy ordering with precise combinatorial counting.

Recommended for interviews: The greedy frequency approach combined with combinatorics is what most interviewers expect. It shows you understand why choosing the highest-frequency characters maximizes beauty and how to correctly count combinations when multiple characters share the same frequency.

Approach 1: Greedy with Frequency Count

Sort the characters of the string based on their frequencies in descending order. Select the top k unique characters and compute the beauty by forming all possible k-subsequences using these k characters. The final result is the number of such subsequences with maximum beauty.

We utilize the collections.Counter to count character frequencies. We sort these frequencies, choose the top k, and calculate their sum as maximum beauty. For counting subsequences with maximum beauty, we multiply the combinations of each chosen character's occurrence, which gives us the count of unique sets of k characters resulting in max beauty.

Code

Python

Complexity

Time Complexity: O(n log n) for sorting the frequencies where n is the number of unique characters in s.
Space Complexity: O(n) for storing character counts and sorted frequencies.

Try this approach in the editor →

Approach 2: Mathematical Combinatorics

Use character frequency counts to find all unique candidates for k-length subsequences with maximum beauty. Compute the number of such subsequences directly using combinatorial mathematics.

We build a frequency map of characters using a HashMap, sort the frequencies, and select the top k frequencies to calculate maximum beauty. We calculate the number of such k-length subsequences using combination calculations derived from frequencies, providing the desired result.

Code

Java

Complexity

Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) due to storage of frequency list and map.

Try this approach in the editor →

Approach 3: Greedy with Frequency Counting

This approach involves first calculating the frequency of each character in the string. Then, we will create all possible k-subsequences using a greedy method that always selects the characters with the highest frequency first.

This Python solution uses a Counter to count frequency of characters. It then sorts these frequencies and selects the k most frequent for the maximum beauty calculation. After calculating max beauty, it computes the number of such subsequences by multiplying the frequencies modulo 10^9 + 7.

Code

Python

Java

Complexity

Time Complexity: O(n + m log m), where n is the length of the string and m is the number of unique characters. Space Complexity: O(m), to store the frequencies.

Try this approach in the editor →

Approach 4: Combinatorial Selection

This approach focuses on generating combinations of indices that correspond to forming k-subsequences. Using combinatorial counting, it calculates ways to choose indices that contribute to the maximum beauty.

This C++ solution calculates frequency of each character, sorts frequencies in descending order, sums top k frequencies to find max beauty, and computes subsequence count as a product of these frequencies modulo 10^9 + 7.

Code

C++

JavaScript

Complexity

Time Complexity: O(n + m log m), Space Complexity: O(m), where m is the number of unique characters.

Try this approach in the editor →

Approach 5: Greedy + Combinatorial Mathematics

First, we use a hash table f to count the occurrence of each character in the string s, i.e., f[c] represents the number of times character c appears in the string s.

Since a k-subsequence is a subsequence of length k in the string s with unique characters, if the number of different characters in f is less than k, then there is no k-subsequence, and we can directly return 0.

Otherwise, to maximize the beauty value of the k-subsequence, we need to make characters with high beauty values appear as much as possible in the k-subsequence. Therefore, we can sort the values in f in reverse order to get an array vs.

We denote the occurrence of the kth character in the array vs as val, and there are x characters with an occurrence of val.

Then we first find out the characters with occurrences greater than val, multiply the occurrences of each character to get the initial answer ans, and update the remaining number of characters to be selected to k. We need to select k characters from x characters, so the answer needs to be multiplied by the combination number C_x^k, and finally multiplied by val^k, i.e., ans = ans times C_x^k times val^k.

Note that we need to use fast power and modulo operations here.

The time complexity is O(n), and the space complexity is O(|\Sigma|). Here, n is the length of the string, and \Sigma is the character set. In this problem, the character set is lowercase letters, so |\Sigma| = 26.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Greedy with Frequency Count

Time Complexity: O(n log n) for sorting the frequencies where n is the number of unique characters in s.
Space Complexity: O(n) for storing character counts and sorted frequencies.

Mathematical Combinatorics

Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) due to storage of frequency list and map.

Greedy with Frequency Counting

Time Complexity: O(n + m log m), where n is the length of the string and m is the number of unique characters. Space Complexity: O(m), to store the frequencies.

Combinatorial Selection

Time Complexity: O(n + m log m), Space Complexity: O(m), where m is the number of unique characters.

Greedy + Combinatorial Mathematics—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Greedy with Frequency CountO(n + m log m)O(m)General solution; simple greedy logic with sorted frequencies
Mathematical CombinatoricsO(n + m log m)O(m)Best when handling many equal-frequency characters
Greedy with Frequency Counting (Optimized)O(n + m log m)O(m)Interview-friendly approach combining greedy selection and modular multiplication
Combinatorial Selection by Frequency GroupsO(n + m log m)O(m)Useful when implementing grouped frequency counting for cleaner tie handling

Video Solution

Leetcode BiWeekly contest 112 - Hard - Count K-Subsequences of a String With Maximum Beauty • Prakhar Agrawal • 1,895 views views

Watch 8 more video solutions →

Frequently Asked Questions

Is Count K-Subsequences of a String With Maximum Beauty easy or hard?
The problem is rated Hard because it combines multiple concepts: greedy optimization, frequency counting, and combinatorial math. Many candidates identify the greedy selection but struggle with counting valid subsequences when frequencies tie. Handling these cases correctly with combinations is the key challenge.
Count K-Subsequences of a String With Maximum Beauty Python/Java solution
In Python, use collections.Counter to count character frequencies, sort them, and multiply the selected frequencies while handling ties with combinatorics. In Java, use a HashMap or int[26] for counting, sort the values, and compute combinations with modular arithmetic. Both implementations follow the same greedy + combinatorial logic.
How to solve Count K-Subsequences of a String With Maximum Beauty in O(n)?
Pure O(n) is difficult because the algorithm usually requires sorting character frequencies. However, since the alphabet size is small, the effective complexity becomes O(n + 26 log 26), which behaves like linear time in practice. The process involves counting frequencies, selecting the largest k values greedily, and computing combinations for ties.
What is the best approach for Count K-Subsequences of a String With Maximum Beauty?
The most effective solution uses a greedy strategy with frequency counting and combinatorics. Count character frequencies, sort them in descending order, and select the top k frequencies to maximize beauty. When multiple characters share the same cutoff frequency, use combinations to count valid selections. This runs in O(n + m log m) time where m is the number of unique characters.
Is Count K-Subsequences of a String With Maximum Beauty asked at Google/Amazon/Meta?
Problems combining greedy selection with combinatorics frequently appear in interviews at companies like Google, Amazon, and Meta. Variants that involve selecting optimal characters, counting subsequences, or handling frequency ties are common in advanced algorithm rounds.
What data structure is used in Count K-Subsequences of a String With Maximum Beauty?
The main data structure is a hash table or frequency array to count occurrences of each character. After counting, a sorted array or priority ordering of frequencies is used to apply the greedy selection. Combinatorial calculations handle cases where multiple characters share the same frequency.
What is the time complexity of Count K-Subsequences of a String With Maximum Beauty?
The optimal solution runs in O(n + m log m) time and O(m) space. Counting frequencies takes O(n), sorting unique character frequencies takes O(m log m), and combinatorial calculations are constant or logarithmic depending on implementation. Since the alphabet size is typically small (like 26 for lowercase letters), the sorting cost is minimal.

Ready to solve this problem?

Practice Count K-Subsequences of a String With Maximum Beauty with our built-in code editor and test cases.

Practice on FleetCode