Sponsored
Sponsored
Use a 2D table to keep track of the longest palindromic subsequence. The idea is to fill out this table by solving smaller subproblems and using their results to build up solutions to bigger ones.
The table, dp[i][j], will store the length of the longest palindromic subsequence in s[i...j]
. Start by assuming that each character is a palindrome of length 1, and fill the table based on whether the characters at the current indices are the same.
Time Complexity: O(n^2), where n is the length of the string, because we need to fill an n x n table.
Space Complexity: O(n^2), for the same reason due to the dp table.
1function longestPalindromeSubseq(s) {
2 const n = s.length;
3 const dp = Array.from({ length: n }, () => Array(n).fill(0));
4 for (let i = n - 1; i >= 0; i--) {
5 dp[i][i] = 1;
6 for (let j = i + 1; j < n; j++) {
7 if (s[i] === s[j]) {
8 dp[i][j] = dp[i + 1][j - 1] + 2;
9 } else {
10 dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
11 }
12 }
13 }
14 return dp[0][n - 1];
15}
16
17console.log(longestPalindromeSubseq("bbbab"));
JavaScript implementation utilizes dynamic arrays and iterates over the string similar to other solutions, which ensures compatibility with various environments.
This approach defines a recursive function that explores all potential palindromic subsequences, using memoization to store results of overlapping subproblems, thereby avoiding redundant calculations. The function checks if the characters at current indices are equal and proceeds based on that, with memoization avoiding recalculations.
Time Complexity: O(n^2), where n is the length of the string due to memoization.
Space Complexity: O(n^2) for the memoization table.
1
In the recursive approach, a helper function checks the characters from both ends of the string, memoizing already computed results to reduce computational overhead. The "memo" array stores results of already solved subproblems.