# Count All Palindromic Subsequence in a given String

Last Updated : 29 Nov, 2023

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.

Examples:

`Input : str = "abcd"Output : 4Explanation :- palindromic  subsequence are : "a" ,"b", "c" ,"d" Input : str = "aab"Output : 4Explanation :- 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)`

### Recursive Approach

Here is the recursive code to the above approach

## C++

 `#include ` `#include `   `using` `namespace` `std;`   `// Function to return the total palindromic subsequence` `int` `Solve(string str, ``int` `i, ``int` `j) {` `    ``if` `(i == j) ``// Base case: when the indices are the same, there is one palindrome` `        ``return` `1;`   `    ``if` `(i > j) ``// Base case: when the first index is greater than the second, there are no palindromes` `        ``return` `0;`   `    ``if` `(str[i] == str[j]) {` `        ``// If the characters at indices i and j are the same, we can form palindromic subsequences` `        ``// by including or excluding both characters, so we add 1 and make recursive calls.` `        ``return` `1 + Solve(str, i + 1, j) + Solve(str, i, j - 1);` `    ``} ``else` `{` `        ``// If the characters at indices i and j are different, we exclude one of them and make recursive calls.` `        ``return` `Solve(str, i + 1, j) + Solve(str, i, j - 1) - Solve(str, i + 1, j - 1);` `    ``}` `}`   `// Driver program` `int` `main() {` `    ``string str = ``"abcb"``;` `    ``cout << ``"Total palindromic subsequence are: "` `<< Solve(str, 0, str.length() - 1) << endl;` `    ``return` `0;` `}`

## Java

 `// Java code to Count Palindromic Subsequence` `// in a given String` `public` `class` `GFG {` `    ``// Function return the total palindromic` `    ``// subsequence` `    ``static` `int` `solve(String str, ``int` `i, ``int` `j)` `    ``{` `        ``if` `(i == j) ``//  base case when index is same` `            ``return` `1``;`   `        ``if` `(i > j)` `            ``return` `0``;`   `        ``if` `(str.charAt(i) == str.charAt(j)) {`   `            ``return` `1` `+ solve(str, i + ``1``, j)` `                ``+ solve(str, i, j - ``1``);` `        ``}`   `        ``else` `            ``return` `solve(str, i + ``1``, j)` `                ``+ solve(str, i, j - ``1``)` `                ``- solve(str, i + ``1``, j - ``1``);` `    ``}`   `    ``// Driver program` `    ``public` `static` `void` `main(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`

## Python3

 `# Function to return the total palindromic subsequence` `def` `solve(s, i, j):` `    ``if` `i ``=``=` `j:` `        ``# Base case: when the indices are the same, there is one palindrome` `        ``return` `1`   `    ``if` `i > j:` `        ``# Base case: when the first index is greater than the second, there are no palindromes` `        ``return` `0`   `    ``if` `s[i] ``=``=` `s[j]:` `        ``# If the characters at indices i and j are the same, we can form palindromic subsequences` `        ``# by including or excluding both characters, so we add 1 and make recursive calls.` `        ``return` `1` `+` `solve(s, i ``+` `1``, j) ``+` `solve(s, i, j ``-` `1``)` `    ``else``:` `        ``# If the characters at indices i and j are different, we exclude one of them and make recursive calls.` `        ``return` `solve(s, i ``+` `1``, j) ``+` `solve(s, i, j ``-` `1``) ``-` `solve(s, i ``+` `1``, j ``-` `1``)`   `# Driver program` `if` `__name__ ``=``=` `"__main__"``:` `    ``s ``=` `"abcb"` `    ``print``(``"Total palindromic subsequences are:"``, solve(s, ``0``, ``len``(s) ``-` `1``))`   `# This code is contributed by shivamgupta310570`

## C#

 `using` `System;`   `public` `class` `GFG` `{` `    ``// Function to return the total palindromic subsequence` `    ``static` `int` `Solve(``string` `str, ``int` `i, ``int` `j)` `    ``{` `        ``if` `(i == j) ``// Base case: when the indices are the same, there is one palindrome` `            ``return` `1;`   `        ``if` `(i > j) ``// Base case: when the first index is greater` `                   ``// than the second, there are no palindromes` `            ``return` `0;`   `        ``if` `(str[i] == str[j])` `        ``{` `            ``// If the characters at indices i and j are the same, ` `            ``// we can form palindromic subsequences` `            ``// by including or excluding both characters, so we add 1 and make recursive calls.` `            ``return` `1 + Solve(str, i + 1, j) + Solve(str, i, j - 1);` `        ``}` `        ``else` `        ``{` `            ``// If the characters at indices i and j are different, ` `            ``// we exclude one of them and make recursive calls.` `            ``return` `Solve(str, i + 1, j) + Solve(str, i, j - 1) - Solve(str, i + 1, j - 1);` `        ``}` `    ``}`   `    ``// Driver program` `    ``public` `static` `void` `Main(``string``[] args)` `    ``{` `        ``string` `str = ``"abcb"``;` `        ``Console.WriteLine(``"Total palindromic subsequence are: "` `+ Solve(str, 0, str.Length - 1));` `    ``}` `}`

## Javascript

 `// Function to return the total palindromic subsequence` `function` `solve(str, i, j) {` `    ``if` `(i === j) ``// Base case: when the indices are the same, there is one palindrome` `        ``return` `1;`   `    ``if` `(i > j) ``// Base case: when the first index is greater than the second, there are no palindromes` `        ``return` `0;`   `    ``if` `(str[i] === str[j]) {` `        ``// If the characters at indices i and j are the same, we can form palindromic subsequences` `        ``// by including or excluding both characters, so we add 1 and make recursive calls.` `        ``return` `1 + solve(str, i + 1, j) + solve(str, i, j - 1);` `    ``} ``else` `{` `        ``// If the characters at indices i and j are different, we exclude one of them and make recursive calls.` `        ``return` `solve(str, i + 1, j) + solve(str, i, j - 1) - solve(str, i + 1, j - 1);` `    ``}` `}`   `// Driver program` `const str = ``"abcb"``;` `console.log(``"Total palindromic subsequences are: "` `+ solve(str, 0, str.length - 1));`

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 ` `#include ` `using` `namespace` `std;`   `// Function return the total palindromic subsequence` `int` `countPS(string str)` `{` `    ``int` `N = str.length();`   `    ``// create a 2D array to store the count of palindromic` `    ``// subsequence` `    ``int` `cps[N + 1][N + 1];` `    ``memset``(cps, 0, ``sizeof``(cps));`   `    ``// palindromic subsequence of length 1` `    ``for` `(``int` `i = 0; i < N; i++)` `        ``cps[i][i] = 1;`   `    ``// check subsequence of length L is palindrome or not` `    ``for` `(``int` `L = 2; L <= N; L++) {` `        ``for` `(``int` `i = 0; i <= N-L; i++) {` `            ``int` `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 program` `int` `main()` `{` `    ``string str = ``"abcb"``;` `    ``cout << ``"Total palindromic subsequence are : "` `         ``<< countPS(str) << endl;` `    ``return` `0;` `}`

## Java

 `// Java code to Count Palindromic Subsequence` `// in a given String` `public` `class` `GFG {` `    ``// Function return the total palindromic` `    ``// subsequence` `    ``static` `int` `countPS(String str)` `    ``{` `        ``int` `N = str.length();`   `        ``// create a 2D array to store the count` `        ``// of palindromic subsequence` `        ``int``[][] cps = ``new` `int``[N][N];`   `        ``// palindromic subsequence of length 1` `        ``for` `(``int` `i = ``0``; i < N; i++)` `            ``cps[i][i] = ``1``;`   `        ``// check subsequence of length L is` `        ``// palindrome or not` `        ``for` `(``int` `L = ``2``; L <= N; L++) {` `            ``for` `(``int` `i = ``0``; i <= N-L; i++) {` `                ``int` `k = 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` `        ``return` `cps[``0``][N - ``1``];` `    ``}`   `    ``// Driver program` `    ``public` `static` `void` `main(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`     `def` `countPS(``str``):`   `    ``N ``=` `len``(``str``)`   `    ``# Create a 2D array to store the count` `    ``# of palindromic subsequence` `    ``cps ``=` `[[``0` `for` `i ``in` `range``(N ``+` `2``)]``for` `j ``in` `range``(N ``+` `2``)]`   `    ``# palindromic subsequence of length 1` `    ``for` `i ``in` `range``(N):` `        ``cps[i][i] ``=` `1`   `    ``# check subsequence of length L` `    ``# is palindrome or not` `    ``for` `L ``in` `range``(``2``, N ``+` `1``):`   `        ``for` `i ``in` `range``(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` `    ``return` `cps[``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` `using` `System;`   `class` `GFG {`   `    ``// Function return the total` `    ``// palindromic subsequence` `    ``static` `int` `countPS(``string` `str)` `    ``{` `        ``int` `N = str.Length;`   `        ``// create a 2D array to store the` `        ``// count of palindromic subsequence` `        ``int``[, ] cps = ``new` `int``[N + 1, N + 1];`   `        ``// palindromic subsequence` `        ``// of length 1` `        ``for` `(``int` `i = 0; i < N; i++)` `            ``cps[i, i] = 1;`   `        ``// check subsequence of length` `        ``// L is palindrome or not` `        ``for` `(``int` `L = 2; L <= N; L++) {` `            ``for` `(``int` `i = 0; i <= N-L; i++) {` `                ``int` `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` `        ``return` `cps[0, N - 1];` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main()` `    ``{` `        ``string` `str = ``"abcb"``;` `        ``Console.Write(``"Total palindromic "` `                      ``+ ``"subsequence are : "` `                      ``+ countPS(str));` `    ``}` `}`   `// This code is contributed by nitin mittal.`

## Javascript

 ``

## PHP

 ``

Output

```Total palindromic subsequence are : 6

```

Time Complexity: O(N2)
Auxiliary Space: O(N2)

## C++

 `// C++ program to counts Palindromic Subsequence` `// in a given String using recursion` `#include ` `using` `namespace` `std;`   `int` `n, dp[1000][1000];` `string str = ``"abcb"``;`   `// Function return the total` `// palindromic subsequence` `int` `countPS(``int` `i, ``int` `j)` `{`   `    ``if` `(i > j)` `        ``return` `0;`   `    ``if` `(dp[i][j] != -1)` `        ``return` `dp[i][j];`   `    ``if` `(i == j)` `        ``return` `dp[i][j] = 1;`   `    ``else` `if` `(str[i] == str[j])` `        ``return` `dp[i][j]` `               ``= countPS(i + 1, j) + ` `                ``countPS(i, j - 1) + 1;`   `    ``else` `        ``return` `dp[i][j] = countPS(i + 1, j) +` `                          ``countPS(i, j - 1) -` `                          ``countPS(i + 1, j - 1);` `}`   `// Driver code` `int` `main()` `{` `    ``memset``(dp, -1, ``sizeof``(dp));` `    ``n = str.size();` `    ``cout << ``"Total palindromic subsequence are : "` `         ``<< countPS(0, n - 1) << endl;` `    ``return` `0;` `}` `// this code is contributed by Kushdeep Mittal`

## Java

 `// Java program to counts Palindromic Subsequence` `// in a given String using recursion`   `class` `GFG {` `    ``static` `int` `n;` `    ``static` `int``[][] dp = ``new` `int``[``1000``][``1000``];`   `    ``static` `String str = ``"abcb"``;`   `    ``// Function return the total` `    ``// palindromic subsequence` `    ``static` `int` `countPS(``int` `i, ``int` `j)` `    ``{`   `        ``if` `(i > j)` `            ``return` `0``;`   `        ``if` `(dp[i][j] != -``1``)` `            ``return` `dp[i][j];` `    `  `        ``if` `(i == j)` `            ``return` `dp[i][j] = ``1``;`   `        ``else` `if` `(str.charAt(i) == str.charAt(j))` `            ``return` `dp[i][j]` `                ``= countPS(i + ``1``, j) + ` `                    ``countPS(i, j - ``1``) + ``1``;`   `        ``else` `            ``return` `dp[i][j] = countPS(i + ``1``, j) + ` `                              ``countPS(i, j - ``1``) -` `                              ``countPS(i + ``1``, j - ``1``);` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``for` `(``int` `i = ``0``; i < ``1000``; i++)` `            ``for` `(``int` `j = ``0``; j < ``1000``; j++)` `                ``dp[i][j] = -``1``;`   `        ``n = str.length();` `        ``System.out.println(``"Total palindromic subsequence"` `                           ``+ ``"are : "` `+ countPS(``0``, n - ``1``));` `    ``}` `}`   `// This code is contributed by Ryuga`

## Python 3

 `# Python 3 program to counts Palindromic` `# Subsequence in a given String using recursion`   `str` `=` `"abcb"`   `# Function return the total` `# palindromic subsequence`     `def` `countPS(i, j):`   `    ``if``(i > j):` `        ``return` `0`   `    ``if``(dp[i][j] !``=` `-``1``):` `        ``return` `dp[i][j]`   `    ``if``(i ``=``=` `j):` `        ``dp[i][j] ``=` `1` `        ``return` `dp[i][j]`   `    ``else` `if` `(``str``[i] ``=``=` `str``[j]):` `        ``dp[i][j] ``=` `(countPS(i ``+` `1``, j) ``+` `                    ``countPS(i, j ``-` `1``) ``+` `1``)` `        ``return` `dp[i][j]` `    ``else``:` `        ``dp[i][j] ``=` `(countPS(i ``+` `1``, j) ``+` `                    ``countPS(i, j ``-` `1``) ``-` `                    ``countPS(i ``+` `1``, j ``-` `1``))` `        ``return` `dp[i][j]`     `# Driver code` `if` `__name__ ``=``=` `"__main__"``:`   `    ``dp ``=` `[[``-``1` `for` `x ``in` `range``(``1000``)]` `          ``for` `y ``in` `range``(``1000``)]`   `    ``n ``=` `len``(``str``)` `    ``print``(``"Total palindromic subsequence are :"``,` `          ``countPS(``0``, n ``-` `1``))`   `# This code is contributed by ita_c`

## C#

 `// C# program to counts Palindromic Subsequence` `// in a given String using recursion` `using` `System;`   `class` `GFG {` `    ``static` `int` `n;` `    ``static` `int``[, ] dp = ``new` `int``[1000, 1000];`   `    ``static` `string` `str = ``"abcb"``;`   `    ``// Function return the total` `    ``// palindromic subsequence` `    ``static` `int` `countPS(``int` `i, ``int` `j)` `    ``{`   `        ``if` `(i > j)` `            ``return` `0;`   `        ``if` `(dp[i, j] != -1)` `            ``return` `dp[i, j];`   `        ``if` `(i == j)` `            ``return` `dp[i, j] = 1;`   `        ``else` `if` `(str[i] == str[j])` `            ``return` `dp[i, j]` `                ``= countPS(i + 1, j) + ` `                ``countPS(i, j - 1) + 1;`   `        ``else` `            ``return` `dp[i, j] = countPS(i + 1, j)` `                              ``+ countPS(i, j - 1)` `                              ``- countPS(i + 1, j - 1);` `    ``}`   `    ``// Driver code` `    ``static` `void` `Main()` `    ``{` `        ``for` `(``int` `i = 0; i < 1000; i++)` `            ``for` `(``int` `j = 0; j < 1000; j++)` `                ``dp[i, j] = -1;`   `        ``n = str.Length;` `        ``Console.Write(``"Total palindromic subsequence"` `                      ``+ ``"are : "` `+ countPS(0, n - 1));` `    ``}` `}`   `// This code is contributed by DrRoot_`

## Javascript

 ``

## PHP

 ` ``\$j``)` `        ``return` `0;` `    `  `    ``if``(``\$dp``[``\$i``][``\$j``] != -1)` `        ``return` `\$dp``[``\$i``][``\$j``];` `    `  `    ``if``(``\$i` `== ``\$j``)` `        ``return` `\$dp``[``\$i``][``\$j``] = 1;` `    `  `    ``else` `if` `(``\$str``[``\$i``] == ``\$str``[``\$j``])` `        ``return` `\$dp``[``\$i``][``\$j``] = countPS(``\$i` `+ 1, ``\$j``) + ` `                             ``countPS(``\$i``, ``\$j` `- 1) + 1;` `    `  `    ``else` `        ``return` `\$dp``[``\$i``][``\$j``] = countPS(``\$i` `+ 1, ``\$j``) + ` `                             ``countPS(``\$i``, ``\$j` `- 1) - ` `                             ``countPS(``\$i` `+ 1, ``\$j` `- 1);` `}`   `// Driver code` `echo` `"Total palindromic subsequence are : "` `. ` `                          ``countPS(0, ``\$n` `- 1); ` `        `  `// This code is contributed by mits` `?>`

Output

```Total palindromic subsequence are : 6

```

Time Complexity : O(N2),
Auxiliary Space: O(N2)