Taro Logo

Count Palindromic Subsequences

#2 Most AskedHard
0 views
Topics:
StringsDynamic Programming

Given a string of digits s, return the number of palindromic subsequences of s having length 5. Since the answer may be very large, return it modulo 109 + 7.

Note:

  • A string is palindromic if it reads the same forward and backward.
  • A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.

Example 1:

Input: s = "103301"
Output: 2
Explanation: 
There are 6 possible subsequences of length 5: "10330","10331","10301","10301","13301","03301". 
Two of them (both equal to "10301") are palindromic.

Example 2:

Input: s = "0000000"
Output: 21
Explanation: All 21 subsequences are "00000", which is palindromic.

Example 3:

Input: s = "9999900000"
Output: 2
Explanation: The only two palindromic subsequences are "99999" and "00000".

Constraints:

  • 1 <= s.length <= 104
  • s consists of digits.

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 length range of the input string `s`, and what character set does it contain (e.g., lowercase English letters only)?
  2. Is the target length of the palindromic subsequences provided as an additional parameter in the function signature, or are we looking for subsequences of all possible lengths?
  3. How should we handle empty strings or inputs where no palindromic subsequence of the specified length exists? Should it return 0?
  4. When counting subsequences, are identical subsequences formed by different character indices counted multiple times or as a single unique subsequence?
  5. Is the modulo value $1,000,000,007$ to be applied at every intermediate addition step to prevent integer overflow?

Brute Force Solution

Approach

To find all the palindromic subsequences in a piece of text using the brute force method, we need to look at every single possible combination of characters we can make by skipping or keeping letters. We then check each of those combinations to see if it reads the same forwards and backwards.

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

  1. Start by listing every possible way to pick out groups of characters from the original text by keeping some letters and ignoring others.
  2. Go through this complete list of character combinations one by one.
  3. For each combination, check if it reads the exact same forwards as it does backwards to see if it is a palindrome.
  4. Every time you find a combination that matches this rule, put a tally mark on a scorecard.
  5. Repeat this checking process for every single combination on your list.
  6. Once you have checked every last possibility, count up all the tally marks to get your final answer.

Code Implementation

def count_palindromic_subsequences(input_string):
    # Generate all possible subsequences by collecting combinations of characters at every index
    subsequence_list = []
    
    for combination_length in range(1, len(input_string) + 1):
        for index_pointer in range(len(input_string)):
            for end_pointer in range(index_pointer + combination_length, len(input_string) + 1):
                subsequence_list.append(input_string[index_pointer:end_pointer])

    # Use a set to track unique combinations since identical subsequences from different indices count separately
    unique_subsequences = []
    for candidate in subsequence_list:
        if candidate not in unique_subsequences:
            unique_subsequences.append(candidate)

    palindrome_tally = 0

    # Evaluate every unique subsequence to determine if it reads identically in reverse
    for sequence_candidate in unique_subsequences:
        reversed_sequence = sequence_candidate[::-1]
        if sequence_candidate == reversed_sequence:
            palindrome_tally += 1

    return palindrome_tally

Big(O) Analysis

Time Complexity
O(2^n * n) – For a string of length n, there are 2^n possible subsequences formed by choosing to include or exclude each character. Generating and checking every single one of these combinations requires going through all subsets. For each of the 2^n subsequences, we must inspect up to n characters to verify if it is a palindrome. This leads to approximately (2^n) * n total operations, which simplifies to the exponential Big O time complexity of O(2^n * n).
Space Complexity
O(2^n) – The brute force method described requires listing every possible combination of characters from the original text of length N, which generates up to 2^n subsequences. Storing this complete list of combinations in memory demands an exponential amount of extra space. Additionally, checking each combination requires recursive stack frames or temporary strings that scale with the length of N. Consequently, the auxiliary memory grows exponentially as the input string size increases.

Optimal Solution

Approach

Instead of checking every single possible grouping of letters, the optimal approach breaks the puzzle down by looking at smaller sections of the word first. By figuring out how many palindromic patterns exist in smaller parts and remembering those answers, we can easily build up to the total count for the full word without doing repetitive work.

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

  1. Begin by looking at the very individual letters on their own, since a single letter is always a palindrome by definition.
  2. Next, look at slightly larger chunks of the word, checking how pairs and triplets of letters can form palindromes together.
  3. As you move to larger sections of the word, check the matching letters at the outer edges of the current section.
  4. If the letters on both ends match each other, use a clever shortcut to combine the patterns found in the smaller inner sections, plus the new palindromes formed by the matching outer pair.
  5. If the outer letters do not match, calculate the count by looking at the overlapping inner sections while carefully removing any duplicated overlap so you do not count the same pattern twice.
  6. Gradually expand your view from the smallest chunks outward until you have covered the entire length of the original word.
  7. Finally, read the accumulated total from the largest scale section, which now holds the complete count of all possible palindromic subsequences.

Code Implementation

def count_palindromic_subsequences(input_string):
    string_length = len(input_string)
    modulo_value = 1000000007
    dp_table = [[0] * string_length for _ in range(string_length)]

    # Base case: every single character is a palindrome of length 1.
    for index in range(string_length):
        dp_table[index][index] = 1

    for current_length in range(2, string_length + 1):
        for start_index in range(string_length - current_length + 1):
            end_index = start_index + current_length - 1

            # Outer matching characters contribute palindromes from inner subproblems.
            if input_string[start_index] == input_string[end_index]:
                dp_table[start_index][end_index] = (dp_table[start_index + 1][end_index] + dp_table[start_index][end_index - 1] + 1) % modulo_value

            # Mismatched outer characters combine overlapping regions while avoiding double counting.
            else:
                dp_table[start_index][end_index] = (dp_table[start_index + 1][end_index] + dp_table[start_index][end_index - 1] - dp_table[start_index + 1][end_index - 1]) % modulo_value

    # The top-right corner holds the total count for the full word length.
    return dp_table[0][string_length - 1]

Big(O) Analysis

Time Complexity
O(n²) – The input size n represents the length of the string, and the cost is driven by building solutions for all possible substrings of varying lengths. We use a two-dimensional table where the rows and columns correspond to the starting and ending indices of these substrings, requiring us to fill in roughly n * n / 2 cells. For each cell, we perform a constant number of operations by looking up previously computed smaller sections and checking the outer boundary characters. Summing the work across all possible pairs of indices results in approximately n * n / 2 operations, which simplifies to O(n²).
Space Complexity
O(N^2) – To remember answers for smaller parts and build up to the full word, the algorithm utilizes a two-dimensional DP table of size N by N, where N is the length of the string. This auxiliary grid stores intermediate results for every possible substring combination. As the input string length N grows, the memory required for this matrix scales quadratically. Therefore, the total extra memory simplifies to Big O of N squared.

Edge Cases

Empty or null string input
How to Handle:
Return zero immediately as no palindromic subsequences can be formed from an empty or null sequence.
String with length smaller than the target subsequence length
How to Handle:
Return zero because there are not enough characters to form a subsequence of the required length.
String with all identical characters
How to Handle:
Calculate the combinations using binomial coefficients since every possible combination of characters forms a valid palindrome.
Maximum length constraints resulting in extremely large numbers
How to Handle:
Apply the modulo 1,000,000,007 operation at each addition and multiplication step to prevent integer overflow.
String containing no repeating characters for lengths greater than one
How to Handle:
Dynamic programming state transitions naturally evaluate to zero for non-matching outer boundaries.
Target subsequence length of one
How to Handle:
Return the length of the string since every single character is trivially a palindromic subsequence of length one.
Target subsequence length matching the string length
How to Handle:
Check if the entire string is a palindrome and return one if true or zero if false.
Large input string causing memory limit exceeded in dynamic programming
How to Handle:
Optimize space complexity by retaining only the necessary previous rows or states instead of a full multi-dimensional table.
0/4 completed