# Counting all possible palindromic subsequence within a string in JavaScript

## Palindrome Sequence:

A string sequence is known as palindrome sequence if it reads the same from front and the back. For instance, 'aba', 'madam, 'did' are all valid palindrome sequences.

We are required to write a JavaScript function that takes in a string as the first and the only argument. The string taken as input is guaranteed to consist of only 'a', 'b', 'c' and 'd'. Our function should count and return the number of all contiguous or noncontiguous palindrome subsequences that appear in the string.

For example −

If the input string is −

const str = 'bccb';

Then the output should be −

const output = 6;

because the palindrome strings here are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'

## Example

The code for this will be −

Live Demo

const str = 'bccb';
const countPalindromes = (str = '') => {
let base = 1000000007;
const dp = Array(str.length).fill([]);
for (let l = 1; l <= str.length; l ++) {
for (let i = 0; i + l - 1 < str.length; i ++) {
let j = i + l - 1;
if (l === 1) {
dp[i][j] = 1;
continue;
}
if (l === 2) {
dp[i][j] = 2;
continue;
}
if (str[i] === str[j]) {
let left = i + 1, right = j - 1;
while (left <= right && str[left] != str[i]) {
left ++;
}
while (left <= right && str[right] != str[i]) {
right --;
}
if (left > right) {
dp[i][j] = dp[i + 1][j - 1] * 2 + 2;
}
else if (left === right) {
dp[i][j] = dp[i + 1][j - 1] * 2 + 1;
} else {
dp[i][j] = dp[i + 1][j - 1] * 2 - dp[left + 1][right - 1];
}
} else {
dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];
}
dp[i][j] = dp[i][j] < 0? dp[i][j] + base : dp[i][j] % base;
}
}
return dp[0][str.length - 1];
};
console.log(countPalindromes(str));

## Output

And the output in the console will be −

6

Updated on: 27-Feb-2021

157 Views

Get certified by completing the course