HardNo. 2842

Count K-Subsequences of a String With Maximum Beauty — LeetCode 2842 Python Solution

Pattern
Greedy
Topics
Greedy, Hash Table, Math, String, Combinatorics
Reading time
3 min

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.

Example

Input
s = "bcca", k = 2
Output
4
Explanation
From s we have f('a') = 1, f('b') = 1, and f('c') = 2.

Python solution

PythonSolution
class Solution:
    def countKSubsequencesWithMaxBeauty(self, s: str, k: int) -> int:
        f = Counter(s)
        if len(f) < k:
            return 0
        mod = 10**9 + 7
        vs = sorted(f.values(), reverse=True)
        val = vs[k - 1]
        x = vs.count(val)
        ans = 1
        for v in vs:
            if v == val:
                break
            k -= 1
            ans = ans * v % mod
        ans = ans * comb(x, k) * pow(val, k, mod) % mod
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(|Σ|)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2842. Count K-Subsequences of a String With Maximum Beauty is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
2514Count AnagramsHard
0012Integer to RomanMedium
0013Roman to IntegerEasy
0166Fraction to Recurring DecimalMedium
0409Longest PalindromeEasy
0423Reconstruct Original Digits from EnglishMedium

Frequently asked questions

How hard is LeetCode 2842. Count K-Subsequences of a String With Maximum Beauty?

LeetCode 2842. Count K-Subsequences of a String With Maximum Beauty is rated Hard on LeetCode.

What is the time complexity of LeetCode 2842. Count K-Subsequences of a String With Maximum Beauty?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 2842. Count K-Subsequences of a String With Maximum Beauty?

The Python solution on this page uses O(|Σ|) auxiliary space.

What topics does LeetCode 2842. Count K-Subsequences of a String With Maximum Beauty cover?

LeetCode 2842. Count K-Subsequences of a String With Maximum Beauty is tagged Greedy, Hash Table, Math, String and Combinatorics on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.