You are given a string ‘S’. Your task is to find the number of subsequences in string ‘S’ which are in the form of “a^p + b^q + c^r”, i.e., it consists of ‘p’ “a” characters, followed by ‘q’ “b” characters, and ‘r’ “c” characters, where ‘p’, ‘q’, and ‘r’ are greater than equal to 1. As the result can be large, return that number modulo 10^9 + 7.
Note :
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. Two subsequences are considered different if the set of array indexes picked for the 2 subsequences are different.
Example :
Let the string be: ababc
The subsequence which can be of form “a^p * b^q * c^r” are: “abc” (p = 1, q = 1, r = 1), “abbc” (p = 1, q = 2, r = 1), “aabc” (p = 2, q = 1, r = 1)
So the count is 5 (“abc” can occur thrice).
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’.
Output Format :
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.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= |S| <= 10^5
S consists of ‘a’, ‘b’, and ‘c’ characters only.
Where |S| denotes the length of ‘S’.
Time limit: 1 sec
2
abc
ababc
1
5
For the first test case:
The subsequence which can be of form “a^p * b^q * c^r” are: “abc” (p = 1, q = 1, r = 1).
So the count is 1.
For the second test case:
The subsequence which can be of form “a^p * b^q * c^r” are: “abc” (p = 1, q = 1, r = 1), “abbc” (p = 1, q = 2, r = 1), “aabc” (p = 2, q = 1, r = 1)
So the count is 5 (“abc” can occur thrice).
2
abbabc
acba
9
0
Check for every possible subsequence present in the string.
The basic idea is to find all the subsequences of the string and check whether it is of a given form or not. For each character of the string we have two choices with us:
Here is the algorithm:
HELPER(‘S’, ‘IDX’, ‘CURR’) (where ‘S’ is the given string, ‘IDX’ is the current index, ‘CURR’ is the current subsequence which is initialized to “”).
isValid(‘CURR’) (where ‘CURR’ is the string to be checked).
O((2 ^N ) * N), where ‘N’ is the size of the string.
Every character of the string has two choices, whether to include it in a subsequence or not. There are total ‘N’ characters, so the number of possible combinations will be 2 * 2 * 2… (‘N’ times). And for every subsequence, we check whether it is of the given form or not, which takes O(N) time. Therefore, the overall time complexity will be O((2 ^ N) * N).
O(N), where ‘N’ is the size of the string.
The recursive stack for the HELPER function can contain at most the length of the string. Therefore, the overall space complexity will be O(N).