


1. A string ‘A’ is a subsequence of a string ‘B’ if ‘A’ can be obtained from ‘B’ by deleting several (possibly, zero or all) characters.
2. A sequence is palindromic if it is equal to the sequence reversed.
3. Two sequences A1, A2,... and B1, B2,... are different if there is some ‘i’ for which ‘Ai’ != ‘Bi’.
The first line of the input contains an integer, 'T’, denoting the number of test cases.
The first line of each test case contains a string ‘S’.
For each test case, print the number of non-empty distinct palindromic subsequences modulo 10^9 + 7.
Print the output of each test case in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |S| <= 3*10^3
Where |S| denotes the length of ‘S’.
Time limit: 1 sec
The basic idea is to find all the subsequences of the string and check whether they are palindrome or not. For each character of the string we have two choices with us:
We also use a set to store the distinct subsequences and print the size of the set minus 1 (empty subsequence).
HELPER(‘S’, ‘IDX’, ‘ST’, ‘CURR’) (where ‘S’ is the given string, ‘IDX’ is the current index, ‘ST’ is the set, ‘CURR’ is the current subsequence which is initialized to “”).
Similarly, call the HELPER function again by including the current character (‘CURR’ + ‘S[IDX]’).
The basic idea is to store the results of the recursive calls to avoid repetition. We can memorize the results of our function calls in an array (say, ‘DP’). We also use an extra array (say, ‘PREV’ and ‘NEXT’) to store the indexes of the characters to avoid duplication of subsequences. Two cases exist during recursive calls:
Let there be two indices, ‘i’ and ‘j’, where ‘i’ and ‘j’ are any subsequence’s first and last indices. Let ‘LEFT’ be the next index of ‘ith’ character and ‘RIGHT’ be the previous ‘jth’ character index.
Here is the algorithm :
HELPER(‘S’, ‘i’, ‘j’, ‘PREV’, ‘NEXT’, ‘DP’) (where ‘S’ is the given string, ‘i’ and ‘j’ is the first and last index of the current subsequence, ‘PREV’ and ‘NEXT’ are the array that stores index and ‘DP’ is the array to store results of function calls).
The idea is similar to the previous approach. In this approach, we use an iterative way to store the count of distinct palindromic subsequences. Like the previous approach, we will create two unordered maps to store the last indices of each character and two arrays to store the previous and next indices for the current character. We also create a ‘DP’ array where ‘DP[i][j]’ represents the count of distinct palindromic subsequences from index ‘i’ to ‘j’. The conditions will be the same as the previous approach.
Here is the algorithm :