A subsequence of a string is achieved by removing some (possibly 0) characters without changing the order of the remaining characters.
You have been given a string 's'.
Find the number of non-empty palindromic subsequences (not necessarily be distinct) in string 's' and return that number modulo 10 ^ 9 + 7.
Input: 's' = "pqqr"
Output: 5
Explanation: The subsequences are:
p
q
q
r
qq
Please note that both "q" are considered different.
The first line contains a string 's'.
Print the number of non-empty palindromic subsequences modulo 10 ^ 9 + 7.
You do not need to print anything; it has already been taken care of. Just implement the given function.
pqqr
5
The subsequences are:
p
q
q
r
qq
Please note that both "q" are considered different.
abc
3
aaaa
15
The expected time complexity is O(|s| ^ 2).
1 <= |s| <= 1000
Where |s| denotes the length of 's'.
Time limit: 1 sec
Can you think of breaking the problem into sub-problems?
The basic idea of this approach is to break the original problem into sub-problems. Let us assume we want to find the number of palindromic subsequences in string 's' whose length is |s|.
Now, let us define a recursive function
count(int i, int j, string &s)Which returns the number of palindromic subsequences in the substring [i:j] of string 's'.
Now, consider the following steps :
We can append 's[i]' and 's[j]' at the front and back respectively in any palindromic subsequence of substring [i + 1, j - 1] and generate a new palindromic subsequence i.e. add count(i + 1, j - 1, s) + 1. Note 1 is added because a pair of characters ('s[i]', 's[j]') will make a palindrome.
O(2 ^ |s|), Where |s| denotes the length of the string 's'.
Since we are using a recursive function that may check all subsequences of the given string. So the overall time complexity will be O(2 ^ |s|).
O(|s|), Where |s| denotes the length of the string 's'.
Since we are using a recursive function where there may be |s| states present in the recursive call stack in the worst case. So the overall space complexity will be O(|s|).