Count K-Subsequences of a String With Maximum Beauty solution and explanation
8 more videos on this problem
Leetcode BiWeekly contest 112 - Hard - Count K-Subsequences of a String With Maximum BeautyPrakhar Agrawal · 25:57 · 1K views
Leetcode biweekly contest 112 | Count K-Subsequences of a String With Maximum Beauty | Hindi ExplainPawan Kumar Giri · 20:39 · 1K views
2842. Count K-Subsequences of a String With Maximum Beauty | Recursion | Leetcode Biweekly 112codingMohan · 34:20 · 1K views
2842. Count K-Subsequences of a String With Maximum Beauty (Leetcode Hard)Programming Live with Larry · 35:12 · 561 views
【每日一题】LeetCode 2842. Count K-Subsequences of a String With Maximum BeautyHuifeng Guan · 15:14 · 446 views
leetcode 2842 [Google Interview Question]. Count K-Subsequences of a String With Maximum BeautyCode-Yao · 10:21 · 213 views
Count K-Subsequences of a String With Maximum Beauty | LeetCode 2842CS567 · 6:56 · 188 views
8050. Count K-Subsequences of a String With Maximum Beauty || Biweekly Contest 112 || LeetcodeAshish Kumar · 17:19 · 187 views
2842. Count K Subsequences of a String With Maximum Beauty (LeetCode Hard) (Python)WYCode · 11:39 · 98 views
The 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
sare:"abbbdd"->"ab"having a beauty off('a') + f('b') = 4"abbbdd"->"ad"having a beauty off('a') + f('d') = 3"abbbdd"->"bd"having a beauty off('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 charactercoccurs ins, 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 * 1051 <= k <= s.lengthsconsists 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.
from collections import Counter
from math import comb
MOD = 10**9 + 7
def count_max_beauty_k_subsequences(s, k):
char_count = Counter(s)
char_freq = sorted(char_count.values(), reverse=True)
max_beauty = sum(char_freq[:k])
num_max_beauty_subseq = 1
available_positions = [freq for freq in char_freq if freq in char_freq[:k]]
for freq in available_positions:
num_max_beauty_subseq *= comb(freq, available_positions.count(freq))
num_max_beauty_subseq %= MOD
return num_max_beauty_subseq
s = "bcca"
k = 2
print(count_max_beauty_k_subsequences(s, k)) # Output: 4We 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.
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.
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.
import java.util.*;
public class MaxBeautyKSubsequence {
public static final int MOD = 1000000007;
public static int countMaxBeautyKSubsequences(String s, int k) {
Map<Character, Integer> freqMap = new HashMap<>();
for (char c : s.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
List<Integer> freqList = new ArrayList<>(freqMap.values());
Collections.sort(freqList, Collections.reverseOrder());
int maxBeauty = 0;
for (int i = 0; i < k; i++) {
maxBeauty += freqList.get(i);
}
long numMaxBeautySubseq = 1;
for (int i = 0; i < k; i++) {
numMaxBeautySubseq = (numMaxBeautySubseq * combinations(freqList.get(i), 1)) % MOD;
}
return (int) numMaxBeautySubseq;
}
private static long combinations(int n, int r) {
if (r > n) return 0;
r = Math.min(r, n - r);
long res = 1;
for (int i = 1; i <= r; i++) {
res = res * (n - i + 1) / i;
}
return res;
}
public static void main(String[] args) {
String s = "bcca";
int k = 2;
System.out.println(countMaxBeautyKSubsequences(s, k)); // Output: 4
}
}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.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) due to storage of frequency list and map.
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.
MOD = 10**9 + 7
from collections import Counter
class Solution:
def maxBeautyKSubsequence(self, s: str, k: int) -> int:
char_count = Counter(s)
freq_sorted = sorted(char_count.values(), reverse=True)
if len(freq_sorted) < k:
return 0
max_beauty = sum(freq_sorted[:k])
subseq_count = 1
for i in range(k):
subseq_count *= freq_sorted[i]
subseq_count %= MOD
return subseq_count
sol = Solution()
print(sol.maxBeautyKSubsequence('bcca', 2)) # Output: 4import java.util.*;
public class Solution {
final static int MOD = 1000000007;
public int maxBeautyKSubsequence(String s, int k) {
HashMap<Character, Integer> charCount = new HashMap<>();
for (char c : s.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
List<Integer> frequencies = new ArrayList<>(charCount.values());
frequencies.sort(Collections.reverseOrder());
if (frequencies.size() < k) return 0;
int maxBeauty = 0;
long subseqCount = 1;
for (int i = 0; i < k; i++) {
maxBeauty += frequencies.get(i);
subseqCount = (subseqCount * frequencies.get(i)) % MOD;
}
return (int) subseqCount;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.maxBeautyKSubsequence("bcca", 2)); // Output: 4
}
}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.
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.
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.
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
#define MOD 1000000007
using namespace std;
class Solution {
public:
int maxBeautyKSubsequence(string s, int k) {
unordered_map<char, int> charCount;
for (auto c : s) {
charCount[c]++;
}
vector<int> frequencies;
for (auto& p : charCount) {
frequencies.push_back(p.second);
}
sort(frequencies.rbegin(), frequencies.rend());
if (frequencies.size() < k) return 0;
int maxBeauty = 0;
long long subseqCount = 1;
for (int i = 0; i < k; i++) {
maxBeauty += frequencies[i];
subseqCount = (subseqCount * frequencies[i]) % MOD;
}
return (int)subseqCount;
}
};
int main() {
Solution sol;
cout << sol.maxBeautyKSubsequence("bcca", 2) << endl; // Output: 4
return 0;
}const MOD = 1e9 + 7;
function maxBeautyKSubsequence(s, k) {
const charCount = {};
for (const char of s) {
charCount[char] = (charCount[char] || 0) + 1;
}
const frequencies = Object.values(charCount).sort((a, b) => b - a);
if (frequencies.length < k) return 0;
let maxBeauty = 0, subseqCount = 1;
for (let i = 0; i < k; i++) {
maxBeauty += frequencies[i];
subseqCount = (subseqCount * frequencies[i]) % MOD;
}
return subseqCount;
}
console.log(maxBeautyKSubsequence("bcca", 2)); // Output: 4This 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.
Time Complexity: O(n + m log m), Space Complexity: O(m), where m is the number of unique characters.
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.
function countKSubsequencesWithMaxBeauty(s: string, k: number): number {
const f: number[] = new Array(26).fill(0);
let cnt = 0;
for (const c of s) {
const i = c.charCodeAt(0) - 97;
if (++f[i] === 1) {
++cnt;
}
}
if (cnt < k) {
return 0;
}
const mod = BigInt(10 ** 9 + 7);
const vs: number[] = f.filter(v => v > 0).sort((a, b) => b - a);
const val = vs[k - 1];
const x = vs.filter(v => v === val).length;
let ans = 1n;
for (const v of vs) {
if (v === val) {
break;
}
--k;
ans = (ans * BigInt(v)) % mod;
}
const c: number[][] = new Array(x + 1).fill(0).map(() => new Array(k + 1).fill(0));
for (let i = 0; i <= x; ++i) {
c[i][0] = 1;
for (let j = 1; j <= Math.min(i, k); ++j) {
c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % Number(mod);
}
}
const qpow = (a: bigint, n: number): bigint => {
let ans = 1n;
for (; n; n >>>= 1) {
if (n & 1) {
ans = (ans * a) % BigInt(mod);
}
a = (a * a) % BigInt(mod);
}
return ans;
};
ans = (((ans * BigInt(c[x][k])) % mod) * qpow(BigInt(val), k)) % mod;
return Number(ans);
}func countKSubsequencesWithMaxBeauty(s string, k int) int {
f := [26]int{}
cnt := 0
for _, c := range s {
f[c-'a']++
if f[c-'a'] == 1 {
cnt++
}
}
if cnt < k {
return 0
}
vs := []int{}
for _, x := range f {
if x > 0 {
vs = append(vs, x)
}
}
sort.Slice(vs, func(i, j int) bool {
return vs[i] > vs[j]
})
const mod int = 1e9 + 7
ans := 1
val := vs[k-1]
x := 0
for _, v := range vs {
if v == val {
x++
}
}
for _, v := range vs {
if v == val {
break
}
k--
ans = ans * v % mod
}
c := make([][]int, x+1)
for i := range c {
c[i] = make([]int, x+1)
c[i][0] = 1
for j := 1; j <= i; j++ {
c[i][j] = (c[i-1][j-1] + c[i-1][j]) % mod
}
}
qpow := func(a, n int) int {
ans := 1
for ; n > 0; n >>= 1 {
if n&1 == 1 {
ans = ans * a % mod
}
a = a * a % mod
}
return ans
}
ans = (ans * c[x][k] % mod) * qpow(val, k) % mod
return ans
}Complexity comparison
| Approach | Complexity |
|---|---|
| Greedy with Frequency Count | Time Complexity: O(n log n) for sorting the frequencies where n is the number of unique characters in |
| Mathematical Combinatorics | Time Complexity: O(n log n) due to sorting. |
| 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 | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy with Frequency Count | O(n + m log m) | O(m) | General solution; simple greedy logic with sorted frequencies |
| Mathematical Combinatorics | O(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 Groups | O(n + m log m) | O(m) | Useful when implementing grouped frequency counting for cleaner tie handling |
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.
