Problem solution · Python

Count K Subsequences of a String with Maximum Beauty

Count K Subsequences of a String with Maximum Beauty: a Python solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Sliding window or two pointers
Source
Kamyu LeetCode Solutions
Length
61 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Count K Subsequences of a String with Maximum Beauty, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 61 lines of Python from the credited upstream file count-k-subsequences-of-a-string-with-maximum-beauty.py.
  • The implementation visibly relies on hash lookup.
  • No explicit loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeCount K Subsequences of a String with Maximum Beauty · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n)# Space: O(1) import collectionsimport random  # greedy, quick select, combinatoricsclass Solution(object):    def countKSubsequencesWithMaxBeauty(self, s, k):        """        :type s: str        :type k: int        :rtype: int        """        MOD = 10**9+7        fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]        def nCr(n, k):            if not (0 <= k <= n):                return 0            while len(inv) <= n:  # lazy initialization                fact.append(fact[-1]*len(inv) % MOD)                inv.append(inv[MOD%len(inv)]*(MOD-MOD//len(inv)) % MOD)  # https://cp-algorithms.com/algebra/module-inverse.html                inv_fact.append(inv_fact[-1]*inv[-1] % MOD)            return (fact[n]*inv_fact[n-k] % MOD) * inv_fact[k] % MOD         def nth_element(nums, n, compare=lambda a, b: a < b):            def tri_partition(nums, left, right, target, compare):                mid = left                while mid <= right:                    if nums[mid] == target:                        mid += 1                    elif compare(nums[mid], target):                        nums[left], nums[mid] = nums[mid], nums[left]                        left += 1                        mid += 1                    else:                        nums[mid], nums[right] = nums[right], nums[mid]                        right -= 1                return left, right             left, right = 0, len(nums)-1            while left <= right:                pivot_idx = random.randint(left, right)                pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)                if pivot_left <= n <= pivot_right:                    return                elif pivot_left > n:                    right = pivot_left-1                else:  # pivot_right < n.                    left = pivot_right+1         cnt = collections.Counter(s)        if len(cnt) < k:            return 0        freqs = cnt.values()        nth_element(freqs, k-1, lambda a, b: a > b)        n = freqs.count(freqs[k-1])        r = sum(freqs[i] == freqs[k-1] for i in xrange(k))        return reduce(lambda a, b: a*b%MOD, (freqs[i] for i in xrange(k)), 1)*nCr(n, r)%MOD 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗