Taro Logo

Count the Number of Good Subsequences

#1 Most AskedMedium
0 views
Topics:
ArraysTwo PointersSliding Windows

You are given a binary string s. A subsequence of s is considered good if it is not empty and has a value that is a power of 5.

  • For example, if s = "1011", then "1", "11", "101", and "1011" are some of its subsequences. Among these, only the subsequence "101" has a value of 5, which is a power of 5.

Return the number of good subsequences in s. Since the answer may be large, return it modulo 109 + 7.

  • A subsequence of a string is formed by deleting some characters (possibly none) of the string.
  • The value of a string is its decimal representation.
  • For example, if s = "101", then its value is 5.

Example 1:

Input: s = "000"
Output: 0
Explanation: There are no good subsequences, so we return 0.

Example 2:

Input: s = "1011"
Output: 5
Explanation: The good subsequences are "1", "1", "101", "11", and "1011".

Example 3:

Input: s = "0110"
Output: 2
Explanation: The good subsequences are "10" and "10".

Constraints:

  • 1 <= s.length <= 104
  • s[i] is either '0' or '1'.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the string `s`, and what character set does it contain (e.g., only lowercase English letters)?
  2. How are subsequences defined in terms of duplicate characters—are subsequences considered identical if they are formed by choosing characters from different indices in the original string?
  3. Should subsequences of length 1 be considered good, and what should be returned if the string is empty?
  4. When calculating the total number of good subsequences, should we count every unique combination of character indices, or unique resulting strings?
  5. Since the output needs to be modulo $10^9 + 7$, should intermediate calculations also be performed modulo $10^9 + 7$ to prevent integer overflow?

Brute Force Solution

Approach

To solve this problem using the brute force approach, we look at every single possible sub-piece of the given word and test whether it qualifies as a good sub-piece. A good sub-piece is defined as one where all of its unique characters appear the exact same number of times.

Here's how the algorithm would work step-by-step:

  1. Start by listing every possible combination of letters that can be formed from the original word by picking characters without changing their relative order.
  2. Look at the first combination you listed and count how many times each different letter appears inside that specific combination.
  3. Check if all of those counts are completely equal to one another.
  4. If the counts match, count this combination as one of your successful findings.
  5. Repeat this exact same counting and checking process for the next combination on your list.
  6. Continue this routine until every single possible combination has been examined.
  7. Add up all the successful findings you discovered along the way and report that final total as your answer.

Code Implementation

class Solution:
    def countGoodSubsequences(self, word: str) -> int:
        from itertools import combinations
        from collections import Counter
        
        total_good_count = 0
        modulo_value = 10**9 + 7
        seen_subsequences = set()

        # Generate every possible subsequence length to check all combinations
        for subsequence_length in range(1, len(word) + 1):
            for index_combination in combinations(range(len(word)), subsequence_length):
                subsequence_string = ''.join(word[index_identifier] for index_identifier in index_combination)
                
                if subsequence_string in seen_subsequences:
                    continue
                seen_subsequences.add(subsequence_string)
                
                character_frequencies = Counter(subsequence_string)
                frequency_values = list(character_frequencies.values())
                
                # Verify if all unique characters appear the exact same number of times
                if len(set(frequency_values)) == 1:
                    total_good_count = (total_good_count + 1) % modulo_value

        # Return the final accumulated count modulo 10^9 + 7 as requested
        return total_good_count

Big(O) Analysis

Time Complexity
O(2^n * n) – For a string of length n, there are 2^n possible subsequences generated by picking characters without changing their relative order. For each of these 2^n combinations, we must inspect the characters and count their frequencies up to n times to check if they are equal. This leads to approximately 2^n * n total operations, which simplifies to O(2^n * n).
Space Complexity
O(N) – To implement the brute force approach described, the algorithm must generate every possible combination of letters from the input word of length N. Storing these combinations or maintaining recursion stack frames for generating them requires auxiliary memory that scales directly with N. Additionally, frequency counting maps or variables used to check character counts take constant space relative to the unique characters, keeping the dominant auxiliary space tied to the combination generation process. Ultimately, the extra memory used simplifies to Big O of N.

Optimal Solution

Approach

To count the good subsequences efficiently, we group identical items together and use combinatorics to calculate how many valid groups can be formed from each frequency. Instead of checking every possible combination one by one, we calculate the totals mathematically based on how often each item appears in the given collection.

Here's how the algorithm would work step-by-step:

  1. First, count how many times each distinct item appears in the given collection.
  2. Group the items by their frequencies so you know, for example, how many items appear once, twice, three times, and so on.
  3. Determine the maximum number of times any single item appears, which tells you the maximum possible size for your subsequences.
  4. For each possible size from one up to that maximum, calculate how many ways you can pick that exact number of items from every group that has at least that many items available.
  5. Combine the mathematical choices for each size, keeping in mind that all chosen groups must contribute the exact same number of items to the subsequence.
  6. Add up the results for all the different valid sizes to get the final total count of good subsequences.
  7. Because the final answer can be very large, make sure to apply the standard mathematical wrapping rule at each step to keep the numbers manageable.

Code Implementation

from collections import Counter


def count_good_subsequences(word):
    modulo_value = 10**9 + 7
    
    character_counts = Counter(word)
    
    frequency_counts = Counter(character_counts.values())
    
    maximum_frequency = max(character_counts.values())
    
    maximum_length = len(word)
    
    combinations_table = [[0] * (maximum_length + 1) for _ in range(maximum_length + 1)]
    
    for row_index in range(maximum_length + 1):
        combinations_table[row_index][0] = 1
        for column_index in range(1, row_index + 1):
            combinations_table[row_index][column_index] = (combinations_table[row_index - 1][column_index - 1] + combinations_table[row_index - 1][column_index]) % modulo_value

    # Precomputing combinations avoids redundant calculations for faster math execution.
    total_good_subsequences = 0
    
    for subsequence_size in range(1, maximum_frequency + 1):
        ways_for_current_size = 1
        
        for item_frequency, group_count in frequency_counts.items():
            if item_frequency >= subsequence_size:
                choices_from_group = combinations_table[item_frequency][subsequence_size]
                ways_for_current_size = (ways_for_current_size * (choices_from_group + 1)) % modulo_value
                
        # Subtracting one removes the empty subsequence counted by default in the product.
        adjusted_ways = (ways_for_current_size - 1 + modulo_value) % modulo_value
        
        total_good_subsequences = (total_good_subsequences + adjusted_ways) % modulo_value
        
    # Modulo arithmetic prevents integer overflow issues during large summations.
    return total_good_subsequences

Big(O) Analysis

Time Complexity
O(n + k^2) – Counting the frequency of each distinct character takes O(n) time where n is the length of the string, and grouping these frequencies takes time proportional to the number of distinct characters k. Then, for each possible subsequence length from 1 up to the maximum frequency k, we iterate through the frequency groups to compute combinations using Pascal's triangle or precomputed factorials. This inner summation leads to approximately k * k / 2 operations for the combinatorial math, which simplifies to O(k^2) worst-case. Combining the linear counting step and the polynomial combination step gives a total time complexity of O(n + k^2).
Space Complexity
O(n) – To analyze the space complexity, let N be the length of the input string or collection. The algorithm requires a hash map or frequency array to count occurrences of each distinct character, which takes O(k) extra space where k is the number of unique characters. Additionally, precomputing combinations using Pascal's triangle or factorials requires auxiliary tables up to size N. Since the number of unique characters k is bounded by the alphabet size, the dominant auxiliary space used by the frequency counts and combinatorics tables scales linearly with the input size N, simplifying to Big O of N.

Edge Cases

String with all identical characters such as aaaaa
How to Handle:
The frequency array will have one non-zero entry, and the logic should sum combinations for that single frequency.
String with all unique characters such as abcde
How to Handle:
Each character has a frequency of 1, resulting in combinations of choosing k characters from distinct frequencies.
Maximum length constraints up to 10 to the 5th power
How to Handle:
Precomputing factorials and modular inverses is required to calculate combinations efficiently in linear time.
Large resulting values exceeding standard integer limits
How to Handle:
All intermediate and final arithmetic operations must be taken modulo 10 to the 9th plus 7.
String with alternating or mixed duplicate frequencies such as aabbcc
How to Handle:
Iterating through all possible common frequencies from 1 to the maximum frequency correctly captures all valid good subsequences.
String containing length of 1
How to Handle:
The single character forms one valid good subsequence of length 1, which the frequency counting and combination logic naturally handles.
0/4 completed