Find how many palindromic subsequences (need not necessarily be distinct) can be formed in a given string. Note that the empty string is not considered a palindrome.
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)
Recursive Approach
Here is the recursive code to the above approach
Java
// Java code to Count Palindromic Subsequence
// in a given String
publicclassGFG {
// Function return the total palindromic
// subsequence
staticintsolve(String str, inti, intj)
{
if(i == j) // base case when index is same
return1;
if(i > j)
return0;
if(str.charAt(i) == str.charAt(j)) {
return1+ solve(str, i + 1, j)
+ solve(str, i, j - 1);
}
else
returnsolve(str, i + 1, j)
+ solve(str, i, j - 1)
- solve(str, i + 1, j - 1);
}
// Driver program
publicstaticvoidmain(String args[])
{
String str = "abcb";
System.out.println(
"Total palindromic "
+ "subsequence are : "
+ solve(str, 0, str.length() - 1));
}
}
// This code is contributed by Ankit Jha
Output
Total palindromic subsequence are : 6
If we draw recursion tree of the above recursive solution, we can observe overlapping Subproblems. Since the problem has overlapping subproblems, we can solve it efficiently using Dynamic Programming. Below is Dynamic Programming based solution.
C++
// Counts Palindromic Subsequence in a given String
#include <cstring>
#include <iostream>
usingnamespacestd;
// Function return the total palindromic subsequence
intcountPS(string str)
{
intN = str.length();
// create a 2D array to store the count of palindromic
// subsequence
intcps[N + 1][N + 1];
memset(cps, 0, sizeof(cps));
// palindromic subsequence of length 1
for(inti = 0; i < N; i++)
cps[i][i] = 1;
// check subsequence of length L is palindrome or not
for(intL = 2; L <= N; L++) {
for(inti = 0; i <= N-L; i++) {
intk = L + i - 1;
if(str[i] == str[k])
cps[i][k]
= cps[i][k - 1] + cps[i + 1][k] + 1;
else
cps[i][k] = cps[i][k - 1] + cps[i + 1][k]
- cps[i + 1][k - 1];
}
}
// return total palindromic subsequence
returncps[0][N - 1];
}
// Driver program
intmain()
{
string str = "abcb";
cout << "Total palindromic subsequence are : "
<< countPS(str) << endl;
return0;
}
Java
// Java code to Count Palindromic Subsequence
// in a given String
publicclassGFG {
// Function return the total palindromic
// subsequence
staticintcountPS(String str)
{
intN = str.length();
// create a 2D array to store the count
// of palindromic subsequence
int[][] cps = newint[N][N];
// palindromic subsequence of length 1
for(inti = 0; i < N; i++)
cps[i][i] = 1;
// check subsequence of length L is
// palindrome or not
for(intL = 2; L <= N; L++) {
for(inti = 0; i <= N-L; i++) {
intk = L + i - 1;
if(str.charAt(i) == str.charAt(k)) {
cps[i][k] = cps[i][k - 1]
+ cps[i + 1][k] + 1;
}else{
cps[i][k] = cps[i][k - 1]
+ cps[i + 1][k]
- cps[i + 1][k - 1];
}
}
}
// return total palindromic subsequence
returncps[0][N - 1];
}
// Driver program
publicstaticvoidmain(String args[])
{
String str = "abcb";
System.out.println("Total palindromic "
+ "subsequence are : "
+ countPS(str));
}
}
// This code is contributed by Sumit Ghosh
Python3
# Python3 code to Count Palindromic
# Subsequence in a given String
# Function return the total
# palindromic subsequence
defcountPS(str):
N =len(str)
# Create a 2D array to store the count
# of palindromic subsequence
cps =[[0fori inrange(N +2)]forj inrange(N +2)]
# palindromic subsequence of length 1
fori inrange(N):
cps[i][i] =1
# check subsequence of length L
# is palindrome or not
forL inrange(2, N +1):
fori inrange(N):
k =L +i -1
if(k < N):
if(str[i] ==str[k]):
cps[i][k] =(cps[i][k -1] +
cps[i +1][k] +1)
else:
cps[i][k] =(cps[i][k -1] +
cps[i +1][k] -
cps[i +1][k -1])
# return total palindromic subsequence
returncps[0][N -1]
# Driver program
str="abcb"
print("Total palindromic subsequence are : ", countPS(str))
# This code is contributed by Anant Agarwal.
C#
// C# code to Count Palindromic Subsequence
// Subsequence in a given String
usingSystem;
classGFG {
// Function return the total
// palindromic subsequence
staticintcountPS(stringstr)
{
intN = str.Length;
// create a 2D array to store the
// count of palindromic subsequence
int[, ] cps = newint[N + 1, N + 1];
// palindromic subsequence
// of length 1
for(inti = 0; i < N; i++)
cps[i, i] = 1;
// check subsequence of length
// L is palindrome or not
for(intL = 2; L <= N; L++) {
for(inti = 0; i <= N-L; i++) {
intk = L + i - 1;
if(k < N) {
if(str[i] == str[k])
cps[i, k] = cps[i, k - 1]
+ cps[i + 1, k] + 1;
else
cps[i, k] = cps[i, k - 1]
+ cps[i + 1, k]
- cps[i + 1, k - 1];
}
}
}
// return total palindromic
// subsequence
returncps[0, N - 1];
}
// Driver Code
publicstaticvoidMain()
{
stringstr = "abcb";
Console.Write("Total palindromic "
+ "subsequence are : "
+ countPS(str));
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// Counts Palindromic Subsequence in
// a given String
// Function return the total
// palindromic subsequence
functioncountPS($str)
{
$N= strlen($str);
// create a 2D array to store the
// count of palindromic subsequence
$cps= array_fill(0, $N+ 1,
array_fill(0, $N+ 1, NULL));
// palindromic subsequence of length 1
for($i= 0; $i< $N; $i++)
$cps[$i][$i] = 1;
// check subsequence of length L
// is palindrome or not
for($L= 2; $L<= $N; $L++)
{
for($i= 0; $i<= $N-$L; $i++)
{
$k= $L+ $i- 1;
if($str[$i] == $str[$k])
$cps[$i][$k] = $cps[$i][$k- 1] +
$cps[$i+ 1][$k] + 1;
else
$cps[$i][$k] = $cps[$i][$k- 1] +
$cps[$i+ 1][$k] -
$cps[$i+ 1][$k- 1];
}
}
// return total palindromic subsequence
return$cps[0][$N- 1];
}
// Driver Code
$str= "abcb";
echo"Total palindromic subsequence are : ".
countPS($str) . "\n";
// This code is contributed by ita_c
?>
Javascript
<script>
// Javascript code to Count Palindromic Subsequence
// in a given String
// Function return the total palindromic
// subsequence
functioncountPS(str)
{
let N = str.length;
// create a 2D array to store the count
// of palindromic subsequence
let cps = newArray(N);
for(let i=0;i<N;i++)
{
cps[i]=newArray(N);
for(let j=0;j<N;j++)
{
cps[i][j]=0;
}
}
// palindromic subsequence of length 1
for(let i = 0; i < N; i++)
cps[i][i] = 1;
// check subsequence of length L is
// palindrome or not
for(let L = 2; L <= N; L++) {
for(let i = 0; i <= N-L; i++) {
let k = L + i - 1;
if(str[i] == str[k]) {
cps[i][k] = cps[i][k - 1]
+ cps[i + 1][k] + 1;
}else{
cps[i][k] = cps[i][k - 1]
+ cps[i + 1][k]
- cps[i + 1][k - 1];
}
}
}
// return total palindromic subsequence
returncps[0][N - 1];
}
// Driver program
let str = "abcb";
document.write("Total palindromic "
+ "subsequence are : "
+ countPS(str));
// This code is contributed by avanitrachhadiya2155
// Javascript program to counts Palindromic Subsequence
// in a given String using recursion
let n;
let dp=newArray(1000);
for(let i=0;i<1000;i++)
{
dp[i]=newArray(1000);
for(let j=0;j<1000;j++)
{
dp[i][j]=-1;
}
}
let str = "abcb";
// Function return the total
// palindromic subsequence
functioncountPS(i,j)
{
if(i > j)
return0;
if(dp[i][j] != -1)
returndp[i][j];
if(i == j)
returndp[i][j] = 1;
elseif(str[i] == str[j])
returndp[i][j]
= countPS(i + 1, j) +
countPS(i, j - 1) + 1;
else
returndp[i][j] = countPS(i + 1, j) +
countPS(i, j - 1) -
countPS(i + 1, j - 1);
}
// Driver code
n = str.length;
document.write("Total palindromic subsequence"
+ "are : "+ countPS(0, n - 1));
// This code is contributed by rag2127
</script>
Output
Total palindromic subsequence are : 6
Time Complexity : O(N2), Auxiliary Space: O(N2)
This article is contributed by Aarti_Rathi and Nishant_sing. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!