Longest Palindromic Subsequence in JavaScript
Last Updated :
30 Jan, 2024
A Longest Palindromic Subsequence in JavaScript refers to the longest sequence of characters within a string that reads the same backward and forward. It's a non-contiguous subsequence, and the goal is to find the maximum length of such subsequences in a given input string.
Example:
Input: str = “GEEKSFORGEEKS”
Output: EEKEE, 5Explanation: The longest palindromic subsequence we can get is of length 5.
There are more than 1 palindromic subsequences of length 5, for example: EEKEE, EESEE, EEFEE, …etc.
Below approaches can be used to achieve this task
Using dynamic programming
In this approach, The palindromicSubsequence function uses dynamic programming to find the longest palindromic subsequence in a given string. It fills the array by comparing characters and their corresponding subsequences. The final result is the longest palindromic subsequence found.
Example: The below code example implements dynamic programming to find the longest palindromic subsequence.
JavaScript
function palindromicSubsequence(str) {
const n = str.length;
const dp = Array.from({ length: n },
() => Array(n).fill(''));
for (let i = 0; i < n; i++) {
dp[i][i] = str[i];
}
for (let cl = 2; cl <= n; cl++) {
for (let index = 0; index + cl - 1 < n; index++) {
const endIndex = index + cl - 1;
const currentChar = str[index];
const endChar = str[endIndex];
if (currentChar === endChar) {
dp[index][endIndex] =
cl === 2 ? currentChar + endChar :
currentChar + dp[index + 1][endIndex - 1]
+ endChar;
} else {
const leftSubstring = dp[index][endIndex - 1];
const bottomSubstring = dp[index + 1][endIndex];
dp[index][endIndex] = leftSubstring.length >
bottomSubstring.length
? leftSubstring : bottomSubstring;
}
}
}
return dp[0][n - 1];
}
const inputStr = "GEEKSFORGEEKS";
const result = palindromicSubsequence(inputStr);
console.log(`Longest Palindromic Subsequence: ${result}`);
console.log(`Longest Palindromic Subsequence Length: ${result.length}`);
OutputLongest Palindromic Subsequence: EEGEE
Longest Palindromic Subsequence Length: 5
Using Recursive method
In this approach, we will use recursion to find the Longest Palindromic Subsequence (LPS) of a given string seq. It explores all possible substrings and returns the longest palindromic subsequence found.
Example: The below code explores all possible palindromic subsequences of the input string using the recursive approach.
JavaScript
function max(x, y) {
return x > y ? x : y;
}
function lps(seq, i, j) {
if (i === j) {
return { length: 1, subsequence: seq[i] };
}
if (i + 1 === j && seq[i] === seq[j]) {
return {
length: 2, subsequence: seq[i]
+ seq[j]
};
}
if (seq[i] === seq[j]) {
const innerResult = lps(seq, i + 1, j - 1);
return {
length: innerResult.length + 2,
subsequence: seq[i] + innerResult.subsequence
+ seq[j],
};
}
const leftResult = lps(seq, i, j - 1);
const rightResult = lps(seq, i + 1, j);
return leftResult.length > rightResult.length ?
leftResult : rightResult;
}
const seq = "GEEKSFORGEEKS";
const n = seq.length;
const result = lps(seq.split(""), 0, n - 1);
console.log
("Longest Palindromic Subsequence: ", result.subsequence);
console.log
("Longest Palindromic Subsequence Length: ", result.subsequence.length);
OutputLongest Palindromic Subsequence: EEGEE
Longest Palindromic Subsequence Length: 5
Similar Reads
Javascript Program to Find the Longest Bitonic Subsequence | DP-15 Given an array arr[0 ... n-1] containing n positive integers, a subsequence of arr[] is called Bitonic if it is first increasing, then decreasing. Write a function that takes an array as argument and returns the length of the longest bitonic subsequence. A sequence, sorted in increasing order is con
3 min read
Javascript Program for Longest subsequence of a number having same left and right rotation Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101"
4 min read
How to Get the Longest String in an Array using JavaScript? Given an array, the task is to get the longest string from the array in JavaScript. Here are a few of the most used techniques discussed with the help of JavaScript. In this article, we will use JavaScript methods to find out the longest string in the array. All approaches are described below with e
5 min read
Javascript Program To Find Length Of The Longest Substring Without Repeating Characters Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
5 min read
Javascript Program for Size of The Subarray With Maximum Sum An array is given, find length of the subarray having maximum sum.Examples : Input : a[] = {1, -2, 1, 1, -2, 1}Output : Length of the subarray is 2Explanation: Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }Output : Leng
2 min read