JavaScript: Longest Palindromic Subsequence
JavaScript String: Exercise-63 with Solution
Longest Palindromic Subsequence
Write a JavaScript function to find the length of the longest palindromic subsequence in a given string.
Subsequences are sequences that can be created by deleting some or all of the elements from another sequence without changing their order.
Test Data:
("aaaba") -> 4
("maadaem") -> 5
("zkksk") -> 3
("ab") -> 1
("") -> ""
Sample Solution:
JavaScript Code:
Output:
4 5 3 1
Explanation:
In the exercise above,
- The function checks if the input 'text' is not a string, in which case it returns a message.
- It gets the length of the input string 'text'.
- If the length of the string is 0, it returns the input string itself.
- It initializes a 2D array 'data' with dimensions 'n x n' filled with zeros, where 'n' is the length of the input string.
- It sets the diagonal elements of 'data' to 1, representing single characters as palindromes.
- It iterates through each character of the input string and calculates the length of the longest palindromic subsequence using dynamic programming.
- It returns the length of the longest palindromic subsequence, which is stored at 'data[0][n - 1]'.
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that finds the length of the longest palindromic subsequence in a string using recursion with memoization.
- Write a JavaScript function that implements a dynamic programming solution to determine the longest palindromic subsequence.
- Write a JavaScript function that returns both the length and the subsequence itself from the given string.
- Write a JavaScript function that handles empty strings and returns a default value when no palindrome exists.
Improve this sample solution and post your code through Disqus.
Previous: Longest Valid Parentheses.
Next: JavaScript Bit Manipulation Exercises Home.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics