Find how many palindromic subsequence (need not necessarily be distinct) can be formed in a given string. Note that the empty string is not considered as a palindrome.
Input : str = "abcd" Output : 4 Explanation :- palindromic subsequence are : "a" ,"b", "c" ,"d" Input : str = "aab" Output : 4 Explanation :- palindromic subsequence are :"a", "a", "b", "aa" Input : str = "aaaa" Output : 15
The above problem can be recursively defined.
Initial Values : i= 0, j= n-1; CountPS(i,j) // Every single character of a string is a palindrome // subsequence if i == j return 1 // palindrome of length 1 // If first and last characters are same, then we // consider it as palindrome subsequence and check // for the rest subsequence (i+1, j), (i, j-1) Else if (str[i] == str[j)] return countPS(i+1, j) + countPS(i, j-1) + 1; else // check for rest sub-sequence and remove common // palindromic subsequences as they are counted // twice when we do countPS(i+1, j) + countPS(i,j-1) return countPS(i+1, j) + countPS(i, j-1) - countPS(i+1, j-1)
If we draw recursion tree of above recursive solution, we can observe overlapping Subprolems. Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic Programming. Below is Dynamic Programming based solution.
Total palindromic subsequence are : 6
Time Complexity : O(N2)
This article is contributed by Nishant_sing(pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Number of palindromic subsequences of length k where k <= 3
- Minimum steps to delete a string after repeated deletion of palindrome substrings
- Friends Pairing Problem
- Find all distinct subset (or subsequence) sums of an array
- Sum of average of all subsets
- Count All Palindrome Sub-Strings in a String | Set 1
- Maximum sum alternating subsequence
- Print all longest common sub-sequences in lexicographical order
- Number of permutation with K inversions
- Count Distinct Subsequences
- Find all distinct palindromic sub-strings of a given string
- Longest Palindromic Substring | Set 1
- Palindrome Partitioning | DP-17
- Longest Palindromic Subsequence | DP-12
- Longest Common Subsequence | DP-4
Improved By : nitin mittal