How to use dynamic programming In Javascript

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 = "w3wiki";
const result = palindromicSubsequence(inputStr);
console.log(`Longest Palindromic Subsequence: ${result}`);
console.log(`Longest Palindromic Subsequence Length: ${result.length}`);


Output

Longest Palindromic Subsequence: EEGEE
Longest Palindromic Subsequence Length: 5

Longest Palindromic Subsequence in JavaScript

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 = “w3wiki”
Output: EEKEE, 5

Explanation: 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.

Similar Reads

Below approaches can be used to achieve this task

Table of Content Using dynamic programming Using Recursive method...

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....

Using Recursive method

...