The Wayback Machine - https://web.archive.org/web/20250131190435/https://www.geeksforgeeks.org/longest-palindromic-subsequence-dp-12/
Open In App

Longest Palindromic Subsequence (LPS)

Last Updated : 19 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a string ‘S’, find the length of the Longest Palindromic Subsequence in it. The Longest Palindromic Subsequence (LPS) is the problem of finding a maximum-length subsequence of a given string that is also a Palindrome.

LPS

Longest Palindromic Subsequence

Examples:

Input: S = “GEEKSFORGEEKS”
Output: 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.

Input: S = “BBABCBCAB”
Output: 7
Explanation: As “BABCBAB” is the longest palindromic subsequence in it. “BBBBB” and “BBCBB” are also palindromic subsequences of the given sequence, but not the longest ones.

Recursive Solution

The naive solution for this problem is to generate all subsequences of the given sequence and find the longest palindromic subsequence. This solution is exponential in terms of time complexity.

Following is a general recursive solution with all cases handled. 

  • Begin matching corner characters at lo = 0, hi = S.length() – 1
  • Case 1: Every single character is a palindrome of length 1. If lo = hi, return 1.
  • Case 2: If there are only 2 characters and match. If lo + 1 = hi and S[lo] = S[hi], return 2
  • Case 3: If first and last characters are not same. Make two recursive calls for lo + 1, hi and lo, hi-1. And return the max of 2 calls.
  • Case 4: If there are more than two characters, and first and last characters are same, recursively call for lo + 1, hi – 1, add 2 to the result and return.

Below is the implementation for the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Returns the length of the longest 
// palindromic subsequence in seq
int lps(const string& s, int lo, int hi) {
  
    // Base Case 1: If there is only 1 character
    if (lo == hi)
        return 1;

    // Base Case 2: If there are only 2 characters
    // and both are same
    if (s[lo] == s[hi] && lo + 1 == hi)
        return 2;

    // If the first and last characters match
    if (s[lo] == s[hi])
        return lps(s, lo + 1, hi - 1) + 2;

    // If the first and last characters do not match
    return max(lps(s, lo, hi - 1), lps(s, lo + 1, hi));
}

int main() {
    string s = "GEEKSFORGEEKS";
    int n = s.size();
    cout << "The length of the LPS is " << lps(s, 0, n - 1);
    return 0;
}
C
#include <stdio.h>
#include <string.h>

int max(int a, int b);

// Returns the length of the longest 
// palindromic subsequence
int lps(const char* s, int lo, int hi) {
  
    // Base Case 1: If there is 1 character
    if (lo == hi)
        return 1;

    // Base Case 2: If there are 2 characters and 
    // both are same
    if (s[lo] == s[hi] && lo + 1 == hi)
        return 2;

    // If the first and last characters match
    if (s[lo] == s[hi])
        return lps(s, lo + 1, hi - 1) + 2;

    // If characters don't match, use max() to 
    // avoid redundant calls
    return max(lps(s, lo, hi - 1), lps(s, lo + 1, hi));
}

int max(int a, int b) {
    return (a > b) ? a : b;
}

int main() {
    char s[] = "GEEKSFORGEEKS";
    int n = strlen(s);
    printf("The length of the LPS is %d", lps(s, 0, n - 1));
    return 0;
}
Java
class GfG {
  
    // Returns length of longest palindromic subsequence
    static int lps(String s, int lo, int hi) {
      
        // Base Case 1: If there is only 1 character
        if (lo == hi)
            return 1;

        // Base Case 2: If there are 2 characters
        // and both are same
        if (s.charAt(lo) == s.charAt(hi) &&
                                        lo + 1 == hi)
            return 2;

        // If the first and last characters match
        if (s.charAt(lo) == s.charAt(hi))
            return lps(s, lo + 1, hi - 1) + 2;

        // If the first and last characters do not match
        return Math.max(lps(s, lo, hi - 1),
                                     lps(s, lo + 1, hi));
    }

    public static void main(String[] args) {
        String s = "GEEKSFORGEEKS";
        int n = s.length();
        System.out.println("The length of the LPS is "
                                       + lps(s, 0, n - 1));
    }
}
Python
# Returns length of longest palindromic subsequence
def lps(s, lo, hi):
    # Base Case 1: If there is only 1 character
    if lo == hi:
        return 1
    
    # Base Case 2: If there are 2 characters and both are same
    if s[lo] == s[hi] and lo + 1 == hi:
        return 2

    # If the first and last characters match
    if s[lo] == s[hi]:
        return lps(s, lo + 1, hi - 1) + 2
    
    # If the first and last characters do not match
    return max(lps(s, lo, hi - 1), lps(s, lo + 1, hi))

s = "GEEKSFORGEEKS"
n = len(s)
print(f"The length of the LPS is {lps(s, 0, n - 1)}")
C#
using System;

class GfG {
    // Returns length of longest palindromic subsequence
    static int lps(string s, int lo, int hi) {
      
        // Base Case 1: If there is only 1 character
        if (lo == hi)
            return 1;

        // Base Case 2: If there are 2 characters
        // and both are same
        if (s[lo] == s[hi] && lo + 1 == hi)
            return 2;

        // If the first and last characters match
        if (s[lo] == s[hi])
            return lps(s, lo + 1, hi - 1) + 2;

        // If the first and last characters do not match
        return Math.Max(lps(s, lo, hi - 1), 
                                      lps(s, lo + 1, hi));
    }

    static void Main() {
        string s = "GEEKSFORGEEKS";
        int n = s.Length;
        Console.WriteLine("The length of the LPS is " 
                                       + lps(s, 0, n - 1));
    }
}
JavaScript
// Returns length of longest palindromic subsequence
function lps(s, lo, hi) {

    // Base Case 1: If there is only 1 character
    if (lo === hi) return 1;

    // Base Case 2: If there are 2 characters
    // and both are same
    if (s[lo] === s[hi] && lo + 1 === hi) return 2;

    // If the first and last characters match
    if (s[lo] === s[hi]) return lps(s, lo + 1, hi - 1) + 2;

    // If the first and last characters do not match
    return Math.max(lps(s, lo, hi - 1), lps(s, lo + 1, hi));
}

let s = "GEEKSFORGEEKS";
let n = s.length;
console.log("The length of the LPS is " + lps(s, 0, n - 1));

Output
The length of the LPS is 5

Time complexity: O(2n), where ‘n’ is the length of the input sequence.
Auxiliary Space: O(n2) as we are using a 2D array to store the solutions of the subproblems.

Using Memoization

We can optimize the above recursive solution using a memo table.

  • The size of the memo table is going to be n x n as there are two parameters that change during recursion and range of the parameters goes from 0 to n-1.
  • We initialize the memo array as -1 and in the recursive code, we make recursive call only when memo[lo][hi] is -1.

Below is the implementation for the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Recursive function to find the length of the 
// longest palindromic subsequence
int lpsRec(const string& s, int lo, int hi, 
           vector<vector<int>>& memo) {
    // Base Case: Single character
    if (lo == hi)
        return 1;

    // Base Case: Two matching characters
    if (s[lo] == s[hi] && lo + 1 == hi)
        return 2;

    // If already computed, return from memo table
    if (memo[lo][hi] != -1)
        return memo[lo][hi];

    // If first and last characters match
    if (s[lo] == s[hi])
        return memo[lo][hi] = lpsRec(s, lo + 1, 
                                     hi - 1, memo) + 2;

    // If they don't match, compute the max
    return memo[lo][hi] = max(lpsRec(s, lo, hi - 1, 
                                     memo), 
                              lpsRec(s, lo + 1, hi, 
                                     memo));
}

// Wrapper function for the LPS calculation
int lps(const string& s) {
    int n = s.size();
    vector<vector<int>> memo(n, vector<int>(n, -1));
    return lpsRec(s, 0, n - 1, memo);
}

int main() {
    string s = "GEEKSFORGEEKS";
    cout << "The length of the LPS is " << lps(s);
    return 0;
}
Java
import java.util.Arrays;

class GfG {
  
    // Recursive function to find the longest palindromic
    // subsequence
    static int lpsRec(String s, int lo, int hi,
                      int[][] memo){
      
        // Base Case: Single character
        if (lo == hi)
            return 1;
      
        // Base Case: Two matching characters
        if (s.charAt(lo) == s.charAt(hi) && lo + 1 == hi)
            return 2;
      
        // If already computed, return from memo
        if (memo[lo][hi] != -1)
            return memo[lo][hi];
      
        // If first and last characters match
        if (s.charAt(lo) == s.charAt(hi))
            return memo[lo][hi]
                = lpsRec(s, lo + 1, hi - 1, memo) + 2;
      
        // If they don't match, compute the max
        return memo[lo][hi]
            = Math.max(lpsRec(s, lo, hi - 1, memo),
                       lpsRec(s, lo + 1, hi, memo));
    }

    // Wrapper function
    static int lps(String s){
        int n = s.length();
        int[][] memo = new int[n][n];
      
        for (int[] row : memo) {
            Arrays.fill(row, -1);
        }
      
        return lpsRec(s, 0, n - 1, memo);
    }

    public static void main(String[] args){
        String s = "GEEKSFORGEEKS";
        System.out.println("The length of the LPS is " 
                                                 + lps(s));
    }
}
Python
# Recursive function to find longest palindromic subsequence
def lpsRec(s, lo, hi, memo):
  
    # Base Case: Single character
    if lo == hi:
        return 1
      
    # Base Case: Two matching characters
    if s[lo] == s[hi] and lo + 1 == hi:
        return 2
      
    # If already computed, return from memo
    if memo[lo][hi] != -1:
        return memo[lo][hi]
      
    # If first and last characters match
    if s[lo] == s[hi]:
        memo[lo][hi] = lpsRec(s, lo + 1, hi - 1, memo) + 2
        return memo[lo][hi]
      
    # If they don't match, compute the max
    memo[lo][hi] = max(lpsRec(s, lo, hi - 1, memo), 
                       lpsRec(s, lo + 1, hi, memo))
    return memo[lo][hi]

# Wrapper function
def lps(s):
    n = len(s)
    memo = [[-1 for _ in range(n)] for _ in range(n)]
    return lpsRec(s, 0, n - 1, memo)

s = "GEEKSFORGEEKS"
print("The length of the LPS is", lps(s))
C#
using System;

class LPS {
    // Recursive function to find longest palindromic subsequence
    static int lpsRec(string s, int lo, int hi, 
                      int[,] memo) {
      
        // Base Case: Single character
        if (lo == hi)
            return 1;
      
        // Base Case: Two matching characters
        if (s[lo] == s[hi] && lo + 1 == hi)
            return 2;
      
        // If already computed, return from memo
        if (memo[lo, hi] != -1)
            return memo[lo, hi];
      
        // If first and last characters match
        if (s[lo] == s[hi])
            return memo[lo, hi] = lpsRec(s, lo + 1, hi - 1, memo) + 2;
      
        // If they don't match, compute the max
        return memo[lo, hi] = Math.Max(lpsRec(s, lo, hi - 1, memo),
                                       lpsRec(s, lo + 1, hi, memo));
    }

    // Wrapper function
    static int lps(string s) {
        int n = s.Length;
        int[,] memo = new int[n, n];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                memo[i, j] = -1;
        return lpsRec(s, 0, n - 1, memo);
    }

    static void Main() {
        string s = "GEEKSFORGEEKS";
        Console.WriteLine("The length of the LPS is " + lps(s));
    }
}
JavaScript
// Recursive function to find the longest palindromic subsequence
function lpsRec(s, lo, hi, memo) {

    // Base Case: Single character
    if (lo === hi) return 1;
    
    // Base Case: Two matching characters
    if (s[lo] === s[hi] && lo + 1 === hi) return 2;
    
    // If already computed, return from memo
    if (memo[lo][hi] !== -1) return memo[lo][hi];
    
    // If first and last characters match
    if (s[lo] === s[hi]) {
        memo[lo][hi] = lpsRec(s, lo + 1, hi - 1, memo) + 2;
        return memo[lo][hi];
    }
    
    // If they don't match, compute the max
    memo[lo][hi] = Math.max(lpsRec(s, lo, hi - 1, memo), 
                            lpsRec(s, lo + 1, hi, memo));
    return memo[lo][hi];
}

// Wrapper function
function lps(s) {
    const n = s.length;
    const memo = Array.from({ length: n }, () => 
                Array(n).fill(-1));
    return lpsRec(s, 0, n - 1, memo);
}

const s = "GEEKSFORGEEKS";
console.log("The length of the LPS is " + lps(s));

Output
The length of the LPS is 5

Time Complexity: O(n2)
Auxiliary Space: O(n2)

Using Bottom-up DP

We can use a bottom-up dp approach to solve the problem iteratively. Our task would be to find the longest palindromic subsequence for every possible substring of the given string s.

We create a 2D dp array where dp[i][j] stores the length of the longest palindromic subsequence for the substring s[i…j]. We fill this table by considering smaller substrings first, then use these results to build answers for larger substrings.

The state transitions are as follows:

  • If s[i] == s[j], then dp[i][j] = dp[i + 1][j – 1] + 2.
  • Otherwise, dp[i][j] = max(dp[i + 1][j], dp[i][j – 1]).

We fill the table iteratively from smaller substrings to larger ones, this will make sure that all subproblems are solved before solving the main problem. Finally, dp[0][n – 1] gives the length of the longest palindromic subsequence for the entire string. This approach avoids recursion by solving smaller subproblems iteratively and building the solution from them.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the length of the longest palindromic subsequence
int lps(const string& s) {
    int n = s.length();
    vector<vector<int>> dp(n, vector<int>(n));

    // Initialize all single character substrings 
    // as palindromes of length 1
    for (int i = 0; i < n; i++) {
        dp[i][i] = 1;
    }

    // Build the DP table for substrings of length 2 and more
    for (int i = n - 2; i >= 0; i--) {
        for (int j = i + 1; j < n; j++) { 

            // If characters at position i and j are the same
            if (s[i] == s[j]) {

                // the length of the palindrome is
                // 2 + the length of the palindrome between them
                dp[i][j] = dp[i + 1][j - 1] + 2;
            } else {

                // Otherwise, take the maximum length
                // from either excluding i or j
                dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
            }
        }
    }

    // The final answer is stored in dp[0][n-1]
    return dp[0][n - 1];
}

int main() {
    string s = "GEEKSFORGEEKS";
    cout << "The length of the LPS is " << lps(s) << endl;
    return 0;
}
Java
class GfG {

    // Function to find the length of the longest palindromic subsequence
    static int lps(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];

        // Initialize all single character substrings 
        // as palindromes of length 1
        for (int i = 0; i < n; i++) {
            dp[i][i] = 1;
        }

        // Build the DP table for substrings of length 2 and more
        for (int i = n - 2; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {

                // If characters at position i and j are the same
                if (s.charAt(i) == s.charAt(j)) {

                    // the length of the palindrome is
                    // 2 + the length of the palindrome between them
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                } else {

                    // Otherwise, take the maximum length
                    // from either excluding i or j
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
                }
            }
        }

        // The final answer is stored in dp[0][n-1]
        return dp[0][n - 1];
    }

    public static void main(String[] args) {
        String s = "GEEKSFORGEEKS";
        System.out.println("The length of the LPS is " + lps(s));
    }
}
Python
# Function to find the length of the longest palindromic subsequence
def lps(s):
    n = len(s)
    dp = [[0 for _ in range(n)] for _ in range(n)]

    # Initialize all single character substrings 
    # as palindromes of length 1
    for i in range(n):
        dp[i][i] = 1

    # Build the DP table for substrings of length 2 and more
    for i in range(n - 2, -1, -1):
        for j in range(i + 1, n):

            # If characters at position i and j are the same
            if s[i] == s[j]:

                # the length of the palindrome is
                # 2 + the length of the palindrome between them
                dp[i][j] = dp[i + 1][j - 1] + 2
            else:

                # Otherwise, take the maximum length
                # from either excluding i or j
                dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])

    # The final answer is stored in dp[0][n-1]
    return dp[0][n - 1]

s = "GEEKSFORGEEKS"
print(f"The length of the LPS is {lps(s)}")
C#
using System;

class GfG {

    // Function to find the length of the longest
    // palindromic subsequence
    static int Lps(string s){
        int n = s.Length;
        int[, ] dp = new int[n, n];

        // Initialize all single character substrings
        // as palindromes of length 1
        for (int i = 0; i < n; i++) {
            dp[i, i] = 1;
        }

        // Build the DP table for substrings of length 2 and
        // more
        for (int i = n - 2; i >= 0; i--) {
            for (int j = i + 1; j < n; j++) {

                // If characters at position i and j are the
                // same
                if (s[i] == s[j]) {

                    // the length of the palindrome is
                    // 2 + the length of the palindrome
                    // between them
                    dp[i, j] = dp[i + 1, j - 1] + 2;
                }
                else {

                    // Otherwise, take the maximum length
                    // from either excluding i or j
                    dp[i, j] = Math.Max(dp[i + 1, j],
                                        dp[i, j - 1]);
                }
            }
        }

        // The final answer is stored in dp[0][n-1]
        return dp[0, n - 1];
    }

    static void Main(string[] args){
        string s = "GEEKSFORGEEKS";
        Console.WriteLine("The length of the LPS is "
                          + Lps(s));
    }
}
JavaScript
// Function to find the length of the longest palindromic
// subsequence
function lps(s)
{
    let n = s.length;
    let dp = Array.from(Array(n), () => Array(n).fill(0));

    // Initialize all single character substrings
    // as palindromes of length 1
    for (let i = 0; i < n; i++) {
        dp[i][i] = 1;
    }

    // Build the DP table for substrings of length 2 and
    // more
    for (let i = n - 2; i >= 0; i--) {
        for (let j = i + 1; j < n; j++) {

            // If characters at position i and j are the
            // same
            if (s[i] === s[j]) {

                // the length of the palindrome is
                // 2 + the length of the palindrome between
                // them
                dp[i][j] = dp[i + 1][j - 1] + 2;
            }
            else {

                // Otherwise, take the maximum length
                // from either excluding i or j
                dp[i][j]
                    = Math.max(dp[i + 1][j], dp[i][j - 1]);
            }
        }
    }

    // The final answer is stored in dp[0][n-1]
    return dp[0][n - 1];
}

let s = "GEEKSFORGEEKS";
console.log("The length of the LPS is " + lps(s));

Output
The length of the LPS is 5

Time Complexity: O(n2)
Auxiliary Space: O(n2)

Using Bottom-up DP (Space Optimization)

This approach optimizes the above buttom-up dp solution by reducing the space complexity. Instead of using a 2D dp[][] array, we only need two 1D arrays: dp[] (for the current row) and dpPrev[] (for the previous row).

If we look at the dp transition states in the above approach, we would realize that the result for current substring s(i…j) that is dp[i][j] is dependent on dp[i + 1][j – 1], dp[i + 1][ j] and dp[i][j – 1].

If we can keep the result of previous row as dpPrev[] then dp[i + 1][j – 1] would become dpPrev[j – 1], similarly, for dp[i + 1][j] would become dpPrev[j] and dp[i][j – 1] would become dp[j -1 ].

Hence, we will traverse from end of the string because doing this we can keep the result of previous row in our dpPrev[]. And after each iteration, we update dpPrev with the current state of dp to be used in the next iteration.

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the length of the longest palindromic subsequence
int lps(const string &s){
    int n = s.size();

    // Create two vectors: one for the current state (dp)
    // and one for the previous state (dpPrev)
    vector<int> dp(n), dpPrev(n);

    // Loop through the string in reverse (starting from the end)
    for (int i = n - 1; i >= 0; --i){

        // A single character is always a palindrome of length 1
        dp[i] = 1;

        // Loop through the characters ahead of i
        for (int j = i + 1; j < n; ++j){

            // If the characters at i and j are the same
            if (s[i] == s[j]){

                // Add 2 to the length of the palindrome between them
                dp[j] = dpPrev[j - 1] + 2;
            }
            else{

                // Take the maximum between excluding either i or j
                dp[j] = max(dpPrev[j], dp[j - 1]);
            }
        }

        // Update dpPrev to the current state of dp
        // for the next iteration
        dpPrev = dp;
    }

    // Answer is the length of longest palindromic subsequence
    // in entire string
    return dp[n - 1];
}

int main(){
    string s = "GEEKSFORGEEKS";
    cout << "The length of the LPS is " << lps(s) << endl;
    return 0;
}
Java
import java.util.*;

class GfG {

    // Function to find the length of the longest palindromic subsequence
    static int lps(String s) {
        int n = s.length();

        // Create two arrays: one for the current state (dp)
        // and one for the previous state (dpPrev)
        int[] dp = new int[n];
        int[] dpPrev = new int[n];

        // Loop through the string in reverse (starting from the end)
        for (int i = n - 1; i >= 0; --i) {

            // A single character is always a palindrome of length 1
            dp[i] = 1;

            // Loop through the characters ahead of i
            for (int j = i + 1; j < n; ++j) {

                // If the characters at i and j are the same
                if (s.charAt(i) == s.charAt(j)) {

                    // Add 2 to the length of the palindrome between them
                    dp[j] = dpPrev[j - 1] + 2;
                } else {

                    // Take the maximum between excluding either i or j
                    dp[j] = Math.max(dpPrev[j], dp[j - 1]);
                }
            }

            // Update dpPrev to the current state of dp
            // for the next iteration
            dpPrev = dp.clone();
        }

        // Answer is the length of longest palindromic subsequence
        // in entire string
        return dp[n - 1];
    }

    public static void main(String[] args) {
        String s = "GEEKSFORGEEKS";
        System.out.println("The length of the LPS is " + lps(s));
    }
}
Python
# Function to find the length of the longest palindromic subsequence
def lps(s):
    n = len(s)

    # Create two lists: one for the current state (dp)
    # and one for the previous state (dpPrev)
    dp = [0] * n
    dpPrev = [0] * n

    # Loop through the string in reverse (starting from the end)
    for i in range(n - 1, -1, -1):

        # A single character is always a palindrome of length 1
        dp[i] = 1

        # Loop through the characters ahead of i
        for j in range(i + 1, n):

            # If the characters at i and j are the same
            if s[i] == s[j]:

                # Add 2 to the length of the palindrome between them
                dp[j] = dpPrev[j - 1] + 2
            else:

                # Take the maximum between excluding either i or j
                dp[j] = max(dpPrev[j], dp[j - 1])

        # Update dpPrev to the current state of dp
        # for the next iteration
        dpPrev = dp[:]

    # Answer is the length of longest palindromic subsequence
    # in entire string
    return dp[n - 1]

s = "GEEKSFORGEEKS"
print(f"The length of the LPS is {lps(s)}")
C#
using System;

class GfG {

    // Function to find the length of the longest palindromic subsequence
    static int Lps(string s) {
        int n = s.Length;

        // Create two arrays: one for the current state (dp)
        // and one for the previous state (dpPrev)
        int[] dp = new int[n];
        int[] dpPrev = new int[n];

        // Loop through the string in reverse (starting from the end)
        for (int i = n - 1; i >= 0; --i) {

            // A single character is always a palindrome of length 1
            dp[i] = 1;

            // Loop through the characters ahead of i
            for (int j = i + 1; j < n; ++j) {

                // If the characters at i and j are the same
                if (s[i] == s[j]) {

                    // Add 2 to the length of the palindrome between them
                    dp[j] = dpPrev[j - 1] + 2;
                } else {

                    // Take the maximum between excluding either i or j
                    dp[j] = Math.Max(dpPrev[j], dp[j - 1]);
                }
            }

            // Update dpPrev to the current state of dp
            // for the next iteration
            dpPrev = (int[])dp.Clone();
        }

        // Answer is the length of longest palindromic subsequence
        // in entire string
        return dp[n - 1];
    }

    static void Main() {
        string s = "GEEKSFORGEEKS";
        Console.WriteLine("The length of the LPS is " + Lps(s));
    }
}
JavaScript
// Function to find the length of the longest palindromic subsequence
function lps(s) {
    let n = s.length;

    // Create two arrays: one for the current state (dp)
    // and one for the previous state (dpPrev)
    let dp = new Array(n).fill(0);
    let dpPrev = new Array(n).fill(0);

    // Loop through the string in reverse (starting from the end)
    for (let i = n - 1; i >= 0; --i) {

        // A single character is always a palindrome of length 1
        dp[i] = 1;

        // Loop through the characters ahead of i
        for (let j = i + 1; j < n; ++j) {

            // If the characters at i and j are the same
            if (s[i] === s[j]) {

                // Add 2 to the length of the palindrome between them
                dp[j] = dpPrev[j - 1] + 2;
            } else {

                // Take the maximum between excluding either i or j
                dp[j] = Math.max(dpPrev[j], dp[j - 1]);
            }
        }

        // Update dpPrev to the current state of dp
        // for the next iteration
        dpPrev = [...dp];
    }

    // Answer is the length of longest palindromic subsequence
    // in entire string
    return dp[n - 1];
}

// Example usage
let s = "GEEKSFORGEEKS";
console.log("The length of the LPS is " + lps(s));

Output
The length of the LPS is 5

Time Complexity: O(n2)
Auxiliary Space: O(n)

Using LCS

Below is an alternate solution.

  1. Find reverse of given string
  2. Return Longest Common Subsequence (LCS) of the string and its reverse.

The time complexity and auxiliary space requirements of this solution are same as the above discussed solutions.

Time Complexity: O(n2)
Auxiliary Space: O(n) if we use space optimized solution of LCS.



Next Article

Similar Reads

three90RightbarBannerImg