#2842

Count K-Subsequences of a String With Maximum Beauty

Hard
Hash TableMathStringGreedySortingCombinatoricsHash MapSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution focuses on counting the frequencies of characters, sorting them, and selecting the top k frequencies to maximize beauty. This avoids generating combinations and directly computes the result.

⚙️

Algorithm

5 steps
  1. 1Step 1: Count the frequency of each character in the string.
  2. 2Step 2: If k is greater than the number of unique characters, return 0.
  3. 3Step 3: Sort the frequencies in descending order.
  4. 4Step 4: Sum the top k frequencies to get the maximum beauty.
  5. 5Step 5: Count how many ways we can choose these characters to achieve the maximum beauty.
solution.py14 lines
1# Full working Python code
2from collections import Counter
3import math
4
5def countKSubsequences(s, k):
6    freq = Counter(s)
7    if k > len(freq): return 0
8    sorted_freq = sorted(freq.values(), reverse=True)
9    max_beauty = sum(sorted_freq[:k])
10    count = 1
11    for i in range(k):
12        count *= freq[sorted_freq[i]]
13        count %= (10**9 + 7)
14    return count

Complexity note: The complexity is O(n log n) due to sorting the frequency counts, while space complexity is O(n) for storing the frequency counts.

  • 1Understanding the frequency of characters is crucial for maximizing beauty.
  • 2Sorting helps in easily accessing the top k frequencies.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.