Open In App

Longest Palindromic Substring using Dynamic Programming

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

Given a string, find the longest substring which is a palindrome. 

Examples: 

Input: Given string :"forgeeksskeegfor", 
Output: "geeksskeeg".
Input: Given string :"Geeks",
Output: "ee".


BRUTE APPROACH: (TABULATION METHOD)

Intuition:

  1. We create a 2-D array to fill the array with appropriate steps.
  2. We fill the matrix using the gap method where we fill the matrix in a diagonal way .
  3. At every step ,we check if the substring generated has meet the condition of palindrome or not.
  4. At every step, we keep a counter variable to store the max length of the palindrome string achieved so far.
  5. Atlast we return the ans.

Implementation:

C++




// C++ program to find the longest palindromic substring in a given string.
#include <iostream>
using namespace std;
 
string longestPalin(string s) {
    // Initialize variables to keep track of the
    // longest palindrome and its length.
    int count = -1;
    string ans = "";
 
    // Get the length of the input string.
    int n = s.length();
 
    // Create a boolean 2D array to store palindrome information.
    bool dp[n][n];
 
    // Iterate through different substring lengths.
    for (int g = 0; g < n; g++) {
        for (int i = 0, j = g; j < n; i++, j++) {
            // Check if the substring is of length 1 (base case).
            if (g == 0) {
                dp[i][j] = true;
            } else if (g == 1) {
                // Check if the substring is of length 2 (base case).
                dp[i][j] = (s[i] == s[j]);
            } else {
                // Check if the current substring is a
                // palindrome based on its ends.
                dp[i][j] = (s[i] == s[j] && dp[i + 1][j - 1]);
            }
 
            // Update the longest palindrome and its length if found.
            if (dp[i][j] && count < j - i + 1) {
                ans = s.substr(i, j - i + 1);
                count = ans.length();
            }
        }
    }
    return ans;
}
 
int main() {
    // Input string
    string str = "forgeeksskeegfor";
     
    // Print the longest palindromic substring.
    cout << longestPalin(str) << endl;
    return 0;
}


Java




// Java program to find the longest palindromic substring in a given string.
 
class LongestPalindrome {
    static String longestPalin(String s) {
        // Initialize variables to keep track of the
        // longest palindrome and its length.
        int count = -1;
        String ans = "";
 
        // Get the length of the input string.
        int n = s.length();
 
        // Create a boolean 2D array to store palindrome information.
        boolean[][] dp = new boolean[n][n];
 
        // Iterate through different substring lengths.
        for (int g = 0; g < n; g++) {
            for (int i = 0, j = g; j < n; i++, j++) {
                // Check if the substring is of length 1 (base case).
                if (g == 0) {
                    dp[i][j] = true;
                } else if (g == 1) {
                    // Check if the substring is of length 2 (base case).
                    dp[i][j] = (s.charAt(i) == s.charAt(j));
                } else {
                    // Check if the current substring is a
                    // palindrome based on its ends.
                    dp[i][j] = (s.charAt(i) == s.charAt(j) && dp[i + 1][j - 1]);
                }
 
                // Update the longest palindrome and its length if found.
                if (dp[i][j] && count < s.substring(i, j + 1).length()) {
                    ans = s.substring(i, j + 1);
                    count = ans.length();
                }
            }
        }
        return ans;
    }
 
    public static void main(String[] args) {
        // Input string
        String str = "forgeeksskeegfor";
         
        // Print the longest palindromic substring.
        System.out.println(longestPalin(str));
    }
}


Python3




# Python program to find the longest palindromic substring in a given string.
 
def longest_palin(s):
    # Initialize variables to keep track
    # of the longest palindrome and its length.
    count = -1
    ans = ""
 
    # Get the length of the input string.
    n = len(s)
     
    # Create a boolean 2D array to
    # store palindrome information.
    dp = [[False] * n for _ in range(n)]
 
    # Iterate through different substring lengths.
    for g in range(n):
        for i in range(n - g):
            j = i + g
            # Check if the substring is of length 1 (base case).
            if g == 0:
                dp[i][j] = True
            # Check if the substring is of length 2 (base case).
            elif g == 1:
                dp[i][j] = (s[i] == s[j])
            else:
                # Check if the current substring is a
                # palindrome based on its ends.
                dp[i][j] = (s[i] == s[j] and dp[i + 1][j - 1])
 
            # Update the longest palindrome and its length if found.
            if dp[i][j] and count < j - i + 1:
                ans = s[i:j + 1]
                count = len(ans)
    return ans
 
# Input string
str = "forgeeksskeegfor"
# Print the longest palindromic substring.
print(longest_palin(str))


C#




// C# program to find the longest palindromic substring in a given string.
using System;
 
public class LongestPalindrome
{
    public static string LongestPalin(string s)
    {
        // Initialize variables to keep track of the
        // longest palindrome and its length.
        int count = -1;
        string ans = "";
 
        // Get the length of the input string.
        int n = s.Length;
 
        // Create a boolean 2D array to store palindrome information.
        bool[,] dp = new bool[n, n];
 
        // Iterate through different substring lengths.
        for (int g = 0; g < n; g++)
        {
            for (int i = 0, j = g; j < n; i++, j++)
            {
                // Check if the substring is of length 1 (base case).
                if (g == 0)
                {
                    dp[i, j] = true;
                }
                // Check if the substring is of length 2 (base case).
                else if (g == 1)
                {
                    dp[i, j] = (s[i] == s[j]);
                }
                else
                {
                    // Check if the current substring is a
                    // palindrome based on its ends.
                    dp[i, j] = (s[i] == s[j] && dp[i + 1, j - 1]);
                }
 
                // Update the longest palindrome and its length if found.
                if (dp[i, j] && count < j - i + 1)
                {
                    ans = s.Substring(i, j - i + 1);
                    count = ans.Length;
                }
            }
        }
        return ans;
    }
 
    public static void Main(string[] args)
    {
        // Input string
        string str = "forgeeksskeegfor";
         
        // Print the longest palindromic substring.
        Console.WriteLine(LongestPalin(str));
    }
}


Javascript




// JavaScript program to find the longest palindromic substring in a given string.
 
function longestPalin(s) {
    // Initialize variables to keep track of the
    // longest palindrome and its length.
    let count = -1;
    let ans = "";
 
    // Get the length of the input string.
    const n = s.length;
 
    // Create a boolean 2D array to store
    // palindrome information.
    const dp = Array.from({ length: n }, () => Array(n).fill(false));
 
    // Iterate through different substring lengths.
    for (let g = 0; g < n; g++) {
        for (let i = 0, j = g; j < n; i++, j++) {
            // Check if the substring is of length 1 (base case).
            if (g === 0) {
                dp[i][j] = true;
            } else if (g === 1) {
                // Check if the substring is of length 2 (base case).
                dp[i][j] = s[i] === s[j];
            } else {
                // Check if the current substring is a
                // palindrome based on its ends.
                dp[i][j] = s[i] === s[j] && dp[i + 1][j - 1];
            }
 
            // Update the longest palindrome and its length if found.
            if (dp[i][j] && count < j - i + 1) {
                ans = s.substring(i, j + 1);
                count = ans.length;
            }
        }
    }
    return ans;
}
 
// Input string
const str = "forgeeksskeegfor";
// Print the longest palindromic substring.
console.log(longestPalin(str));


Output

geeksskeeg


Time Complexity:  O(N^2), where N is the length of string
Space Complexity: O(N^2) since have created a 2-D array.

Common mistake: Wrong Approach:   

Some people will be tempted to come up with a O(n) time complexity quick solution, which is unfortunately flawed (however can be corrected easily):

 (i)Reverse S and store it in S’. 
 (ii)Find the longest common substring between S and S’  which must also be the longest palindromic substring.

This seemed to work, let’s see some examples below.

For example, S = “caba” then  S’ = “abac”.

The longest common substring between S and S’ is “aba”, which is the answer.

Let’s try another example: S = “abacdfgdcaba” then S’ = “abacdgfdcaba”.

The longest common substring between S and S’ is “abacd”. Clearly, this is not a valid palindrome.

Correct Approach:

We could see that the longest common substring method fails when there exists a reversed copy of a non-palindromic substring in some other part of S. To rectify this, each time we find a longest common substring candidate, we check if the substring’s indices are the same as the reversed substring’s original indices. If it is, then we attempt to update the longest palindrome found so far; if not, we skip this and find the next candidate. This gives us an O(n^2) Dynamic Programming solution which uses O(n^2) space (which could be improved to use O(n) space).

Dynamic programming Approach: Dynamic programming solution is already discussed here in the previous post. The time complexity of the Dynamic Programming based solution is O(n^2) and it requires O(n^2) extra space. We can find the longest palindrome substring( LPS ) in (n^2) time with O(1) extra space. 

The algorithm below is very simple and easy to understand. The idea is to Fix a center and expand in both directions for longer palindromes and keep track of the longest palindrome seen so far.

ALGO:

  1. Maintain a variable ‘ maxLength = 1 ‘ (for storing LPS length) and ‘ start =0 ‘ (for storing starting index of LPS ).
  2. The idea is very simple, we will traverse through the entire string with i=0 to i<(length of string).
    1. while traversing, initialize ‘lowand ‘highpointer such that low= i-1 and high= i+1.
    2. keep incrementing ‘high’ until str[high]==str[i] .
    3. similarly keep decrementing ‘low’ until str[low]==str[i].
    4. finally we will keep incrementing ‘high’ and decrementing ‘low’ until str[low]==str[high].
    5. calculate length=high-low-1, if length > maxLength then maxLength = length and start = low+1 .
  3. Print the LPS and return maxLength.
     

C++




// A O(n^2) time and O(1) space program to
// find the longest palindromic substring
// easy to understand as compared to previous version.
#include <bits/stdc++.h>
using namespace std;
 
// A utility function to print
// a substring str[low..high]
// This function prints the
// longest palindrome substring (LPS)
// of str[]. It also returns the
// length of the longest palindrome
int longestPalSubstr(string str)
{
    int n = str.size(); // calculating size of string
    if (n < 2)
        return n; // if string is empty then size will be 0.
                  // if n==1 then, answer will be 1(single
                  // character will always palindrome)
 
    int maxLength = 1, start = 0;
    int low, high;
    for (int i = 0; i < n; i++) {
        low = i - 1;
        high = i + 1;
        while (high < n
               && str[high] == str[i]) // increment 'high'
            high++;
 
        while (low >= 0
               && str[low] == str[i]) // decrement 'low'
            low--;
 
        while (low >= 0 && high < n
               && str[low] == str[high]) {
            low--;
            high++;
        }
 
        int length = high - low - 1;
        if (maxLength < length) {
            maxLength = length;
            start = low + 1;
        }
    }
 
    cout << "Longest palindrome substring is: ";
    cout << str.substr(start, maxLength);
    return maxLength;
}
 
// Driver program to test above functions
int main()
{
    string str = "forgeeksskeegfor";
    cout << "\nLength is: " << longestPalSubstr(str)
         << endl;
    return 0;
}


C




// A O(n^2) time and O(1) space
// program to find the longest
// palindromic substring
#include <stdio.h>
#include <string.h>
 
// A utility function to print
// a substring str[low..high]
void printSubStr(char* str, int low, int high)
{
    for (int i = low; i <= high; ++i)
        printf("%c", str[i]);
}
 
// This function prints the longest
// palindrome substring (LPS)
// of str[]. It also returns the
// length of the longest palindrome
int longestPalSubstr(char* str)
{
    int n = strlen(str); // calculating size of string
    if (n < 2)
        return n; // if string is empty then size will be 0.
                  // if n==1 then, answer will be 1(single
                  // character will always palindrome)
 
    int maxLength = 1, start = 0;
    int low, high;
    for (int i = 0; i < n; i++) {
        low = i - 1;
        high = i + 1;
        while (high < n
               && str[high] == str[i]) // increment 'high'
            high++;
 
        while (low >= 0
               && str[low] == str[i]) // decrement 'low'
            low--;
 
        while (low >= 0 && high < n
               && str[low] == str[high]) {
            low--; // decrement low
            high++; // increment high
        }
 
        int length = high - low - 1;
        if (maxLength < length) {
            maxLength = length;
            start = low + 1;
        }
    }
    printf("Longest palindrome substring is: ");
    printSubStr(str, start, start + maxLength - 1);
    return maxLength;
}
 
// Driver program to test above functions
int main()
{
    char str[] = "forgeeksskeegfor";
    printf("\nLength is: %d", longestPalSubstr(str));
    return 0;
}


Java




// Java implementation of O(n^2)
// time and O(1) space method
// to find the longest palindromic substring
public class LongestPalinSubstring {
   
    // This function prints the
    // longest palindrome substring
    // (LPS) of str[]. It also
    // returns the length of the
    // longest palindrome
    static int longestPalSubstr(String str)
    {
        int n = str.length(); // calculating size of string
        if (n < 2)
            return n; // if string is empty then size will be 0.
                  // if n==1 then, answer will be 1(single
                  // character will always palindrome)
 
        int maxLength = 1,start=0;
        int low, high;
        for (int i = 0; i < n; i++) {
            low = i - 1;
            high = i + 1;
            while ( high < n && str.charAt(high) == str.charAt(i)) //increment 'high'                                  
                high++;
       
            while ( low >= 0 && str.charAt(low) == str.charAt(i)) // decrement 'low'                   
                low--;
       
            while (low >= 0 && high < n && str.charAt(low) == str.charAt(high) ){
                  low--;
                high++;
        }
 
        int length = high - low - 1;
        if (maxLength < length){
            maxLength = length;
            start=low+1;
        }
    }   
    System.out.print("Longest palindrome substring is: ");
    System.out.println(str.substring(start, start + maxLength ));
    return maxLength;
       
 }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
 
        String str = "forgeeksskeegfor";
        System.out.println("Length is: "
                           + longestPalSubstr(str));
    }
}


Python3




# A O(n ^ 2) time and O(1) space program to find the
# longest palindromic substring
 
# This function prints the longest palindrome substring (LPS)
# of str[]. It also returns the length of the longest palindrome
 
 
def longestPalSubstr(string):
    n = len(string) # calculating size of string
    if (n < 2):
        return n # if string is empty then size will be 0.
                  # if n==1 then, answer will be 1(single
                  # character will always palindrome)
    start=0
    maxLength = 1
    for i in range(n):
        low = i - 1
        high = i + 1
        while (high < n and string[high] == string[i] ):                              
            high=high+1
       
        while (low >= 0 and string[low] == string[i] ):                
            low=low-1
       
        while (low >= 0 and high < n and string[low] == string[high] ):
          low=low-1
          high=high+1
         
     
        length = high - low - 1
        if (maxLength < length):
            maxLength = length
            start=low+1
             
    print ("Longest palindrome substring is:",end=" ")
    print (string[start:start + maxLength])
     
    return maxLength
     
# Driver program to test above functions
string = ("forgeeksskeegfor")
print("Length is: " + str(longestPalSubstr(string)))


C#




// C# implementation of O(n^2) time
// and O(1) space method to find the
// longest palindromic substring
using System;
 
class GFG {
 
    // This function prints the longest
    // palindrome substring (LPS) of str[].
    // It also returns the length of the
    // longest palindrome
    public static int longestPalSubstr(string str)
    {
        int n = str.Length; // calculating size of string
        if (n < 2)
            return n; // if string is empty then size will be 0.
                  // if n==1 then, answer will be 1(single
                  // character will always palindrome)
 
        int maxLength = 1,start=0;
        int low, high;
        for (int i = 0; i < n; i++) {
            low = i - 1;
            high = i + 1;
            while ( high < n && str[high] == str[i] ) //increment 'high'                                  
                high++;
       
            while ( low >= 0 && str[low] == str[i]) // decrement 'low'                   
                low--;
       
            while (low >= 0 && high < n && str[low] == str[high] ){
                  low--;
                high++;
        }
 
        int length = high - low - 1;
        if (maxLength < length){
            maxLength = length;
            start=low+1;
        }
    }   
    Console.Write("Longest palindrome substring is: ");
    Console.WriteLine(str.Substring(start, maxLength));
    return maxLength;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string str = "forgeeksskeegfor";
        Console.WriteLine("Length is: "
                          + longestPalSubstr(str));
    }
}


Javascript




<script>
 
// A O(n^2) time and O(1) space program to
// find the longest palindromic substring
// easy to understand as compared to previous version.
 
// A utility function to print
// a substring str[low..high]
// This function prints the
// longest palindrome substring (LPS)
// of str[]. It also returns the
// length of the longest palindrome
function longestPalSubstr(str)
{
    let n = str.length; // calculating size of string
    if (n < 2)
        return n; // if string is empty then size will be 0.
                // if n==1 then, answer will be 1(single
                // character will always palindrome)
 
    let maxLength = 1,start=0;
    let low, high;
    for (let i = 0; i < n; i++) {
        low = i - 1;
        high = i + 1;
        while ( high < n && str[high] == str[i]) //increment 'high'                               
            high++;
     
        while ( low >= 0 && str[low] == str[i]) // decrement 'low'               
            low--;
     
        while (low >= 0 && high < n && str[low] == str[high]){
            low--;
            high++;
        }
 
        let length = high - low - 1;
        if (maxLength < length) {
            maxLength = length;
            start=low+1;
        }
    }
     
    document.write("Longest palindrome substring is: ");
    document.write(str.substring(start,maxLength+start));
    return maxLength;
}
 
// Driver program to test above functions
 
let str = "forgeeksskeegfor";
document.write("</br>","Length is: " + longestPalSubstr(str),"</br>");
 
 
</script>


Output

Longest palindrome substring is: geeksskeeg
Length is: 10


Complexity Analysis:  

  • Time complexity: O(n^2), where n is the length of the input string. 
    Outer Loop that traverses through the entire string, and Inner Loop that is used to expand from i .
  • Auxiliary Space: O(1). 
    No extra space is needed.

The Above approach is a cleaner way.

The function implementation to print the LPS and return the maxLength is given below:

C++




// A O(n^2) time and O(1) space program to
// find the longest palindromic substring
// easy to understand as compared to previous version.
 
#include <bits/stdc++.h>
using namespace std;
 
int maxLength; // variables to store and
string res; // update  maxLength and res
 
// A utility function to get the longest palindrome
// starting and expanding out from given center indices
void cSubUtil(string& s, int l, int r)
{
    // check if the indices lie in the range of string
    // and also if it is palindrome
    while (l >= 0 && r < s.length() && s[l] == s[r]) {
        // expand the boundary
        l--;
        r++;
    }
    // if it's length is greater than maxLength update
    // maxLength and res
    if (r - l - 1 >= maxLength) {
        res = s.substr(l + 1, r - l - 1);
        maxLength = r - l - 1;
    }
    return;
}
// A function which takes a string prints the LPS and
// returns the length of LPS
int longestPalSubstr(string str)
{
    res = "";
    maxLength = 1;
    // for every index in the string check palindromes
    // starting from that index
    for (int i = 0; i < str.length(); i++) {
        // check for odd length palindromes
        cSubUtil(str, i, i);
        // check for even length palindromes
        cSubUtil(str, i, i + 1);
    }
 
    cout << "Longest palindrome substring is: ";
    cout << res << "\n";
 
    return maxLength;
}
 
// Driver program to test above functions
int main()
{
    string str = "forgeeksskeegfor";
    cout << "\nLength is: " << longestPalSubstr(str)
         << endl;
    return 0;
}


Java




// Java implementation of O(n^2)
// time and O(1) space method
// to find the longest palindromic substring
 
public class LongestPalinSubstring {
 
    static int maxLength; // variables to store and
    static String res; // update  maxLength and res
 
    // A utility function to get the longest palindrome
    // starting and expanding out from given center indices
    static void cSubUtil(String s, int l, int r)
    {
        // check if the indices lie in the range of string
        // and also if it is palindrome
        while (l >= 0 && r < s.length()
               && s.charAt(l) == s.charAt(r)) {
            // expand the boundary
            l--;
            r++;
        }
        // if it's length is greater than maxLength update
        // maxLength and res
        if (r - l - 1 >= maxLength) {
            res = s.substring(l + 1, r);
            maxLength = r - l - 1;
        }
        return;
    }
    // A function which takes a string prints the LPS and
    // returns the length of LPS
    static int longestPalSubstr(String str)
    {
        res = "";
        maxLength = 1;
        // for every index in the string check palindromes
        // starting from that index
        for (int i = 0; i < str.length(); i++) {
            // check for odd length palindromes
            cSubUtil(str, i, i);
            // check for even length palindromes
            cSubUtil(str, i, i + 1);
        }
        System.out.print(
            "Longest palindrome substring is: ");
        System.out.println(res);
        return maxLength;
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
 
        String str = "forgeeksskeegfor";
        System.out.println("Length is: "
                           + longestPalSubstr(str));
    }
}


Python3




# Python 3 implementation of O(n^2)
# time and O(1) space method
# to find the longest palindromic substring
class LongestPalinSubstring :
    maxLength = 0
     
    # variables to store and
    res = None
     
    # update  maxLength and res
    # A utility function to get the longest palindrome
    # starting and expanding out from given center indices
    @staticmethod
    def cSubUtil( s,  l,  r) :
       
        # check if the indices lie in the range of string
        # and also if it is palindrome
        while (l >= 0 and r < len(s) and s[l] == s[r]) :
           
            # expand the boundary
            l -= 1
            r += 1
             
        # if it's length is greater than maxLength update
        # maxLength and res
        if (r - l - 1 >= LongestPalinSubstring.maxLength) :
            LongestPalinSubstring.res = s[l + 1:r]
            LongestPalinSubstring.maxLength = r - l - 1
        return
       
    # A function which takes a string prints the LPS and
    # returns the length of LPS
    @staticmethod
    def  longestPalSubstr( str) :
        LongestPalinSubstring.res = ""
        LongestPalinSubstring.maxLength = 1
         
        # for every index in the string check palindromes
        # starting from that index
        i = 0
        while (i < len(str)) :
           
            # check for odd length palindromes
            LongestPalinSubstring.cSubUtil(str, i, i)
             
            # check for even length palindromes
            LongestPalinSubstring.cSubUtil(str, i, i + 1)
            i += 1
        print("Longest palindrome substring is: ", end ="")
        print(LongestPalinSubstring.res)
        return LongestPalinSubstring.maxLength
       
    # Driver program to test above function
    @staticmethod
    def main( args) :
        str1 = "forgeeksskeegfor"
        print("Length is: " + str(LongestPalinSubstring.longestPalSubstr(str1)))
     
if __name__=="__main__":
    LongestPalinSubstring.main([])
     
    # This code is contributed by phasing17.


C#




// C# implementation of O(n^2) time
// and O(1) space method to find the
// longest palindromic substring
using System;
 
class GFG {
 
    static int maxLength; // variables to store and
    static string res; // update  maxLength and res
 
    // A utility function to get the longest palindrome
    // starting and expanding out from given center indices
    public static void cSubUtil(string s, int l, int r)
    {
        // check if the indices lie in the range of string
        // and also if it is palindrome
        while (l >= 0 && r < s.Length && s[l] == s[r]) {
            // expand the boundary
            l--;
            r++;
        }
        // if it's length is greater than maxLength update
        // maxLength and res
        if (r - l - 1 >= maxLength) {
            res = s.Substring(l + 1, r - l - 1);
            maxLength = r - l - 1;
        }
        return;
    }
    // A function which takes a string prints the LPS and
    // returns the length of LPS
    public static int longestPalSubstr(string str)
    {
        res = "";
        maxLength = 1;
        // for every index in the string check palindromes
        // starting from that index
        for (int i = 0; i < str.Length; i++) {
            // check for odd length palindromes
            cSubUtil(str, i, i);
            // check for even length palindromes
            cSubUtil(str, i, i + 1);
        }
 
        Console.Write("Longest palindrome substring is: ");
        Console.WriteLine(res);
        return maxLength;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string str = "forgeeksskeegfor";
        Console.WriteLine("Length is: "
                          + longestPalSubstr(str));
    }
}


Javascript




// A O(n^2) time and O(1) space program to
// find the longest palindromic substring
// easy to understand as compared to previous version.
 
let maxLength = 0; // variables to store and
let res = ""; // update  maxLength and res
 
// A utility function to get the longest palindrome
// starting and expanding out from given center indices
function cSubUtil(s, l, r) {
    // check if the indices lie in the range of string
    // and also if it is palindrome
    while (l >= 0 && r < s.length && s[l] === s[r]) {
        // expand the boundary
        l--;
        r++;
    }
    // if it's length is greater than maxLength update
    // maxLength and res
    if (r - l - 1 >= maxLength) {
        res = s.substring(l + 1, r);
        maxLength = r - l - 1;
    }
    return;
}
// A function which takes a string prints the LPS and
// returns the length of LPS
function longestPalSubstr(str) {
    res = "";
    maxLength = 1;
    // for every index in the string check palindromes
    // starting from that index
    for (let i = 0; i < str.length; i++) {
        // check for odd length palindromes
        cSubUtil(str, i, i);
        // check for even length palindromes
        cSubUtil(str, i, i + 1);
    }
 
    console.log("Longest palindrome substring is: " + res);
 
    return maxLength;
}
 
// Driver program to test above functions
let str = "forgeeksskeegfor";
console.log("\nLength is: " + longestPalSubstr(str));
 
// This code is contributed by akashish__


Output

Longest palindrome substring is: geeksskeeg

Length is: 10




Similar Reads

Longest Palindromic Substring using Palindromic Tree | Set 3
Given a string, find the longest substring which is a palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”. Prerequisite : Palindromic Tree | Longest Palindromic Substring Structure of Palindromic Tree : The palindromic Tree’s actual structure is close to the directed graph. It is actually a merged s
15+ min read
Longest Palindromic Substring using hashing in O(nlogn)
Given a string S, The task is to find the longest substring which is a palindrome using hashing in O(N log N) time. Input: S: ”forgeeksskeegfor”, Output: “geeksskeeg” Input: S: ”Geeks”, Output: “ee” Hashing to Solve the Problem:The hashing approach to solving the longest palindromic substring problem uses a hash table to store the characters of the
11 min read
Distinct palindromic sub-strings of the given string using Dynamic Programming
Given a string str of lowercase alphabets, the task is to find all distinct palindromic sub-strings of the given string. Examples: Input: str = "abaaa" Output: 5 Palindromic sub-strings are "a", "aa", "aaa", "aba" and "b" Input: str = "abcd" Output: 4 Approach: The solution to this problem has been discussed here using Manacher’s algorithm. However
8 min read
Minimum length of substring whose rotation generates a palindromic substring
Given a string str, the task is to find the minimum length of substring required to rotate that generates a palindromic substring from the given string. Examples: Input: str = "abcbd" Output: 0 Explanation: No palindromic substring can be generated. There is no repeated character in the string. Input: str = "abcdeba" Output: 3 Explanation: Rotate s
7 min read
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 3
In Manacher's Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. Here we will implement the same.We have seen that there are no new character comparison needed in case 1 and case 2. In case 3 and case 4, necessary new comparison are needed. In followi
15+ min read
Longest palindromic string possible after removal of a substring
Given a string str, the task is to find the longest palindromic string that can be obtained from it after removing a substring. Examples: Input: str = "abcdefghiedcba" Output: "abcdeiedcba" Explanation: Removal of substring "fgh" leaves the remaining string palindromic Input: str = "abba" Output: "abba" Explanation: Removal of substring "" as the g
11 min read
Rearrange string to obtain Longest Palindromic Substring
Given string str, the task is to rearrange the given string to obtain the longest palindromic substring. Examples: Input: str = “geeksforgeeks”Output: eegksfskgeeorExplanation: eegksfskgee is the longest palindromic substring after rearranging the string.Therefore, the required output is eegksfskgeeor. Input: str = “engineering”Output: eginenigenr
9 min read
Generate an N-length string having longest palindromic substring of length K
Given two integers N and K (K ? N), the task is to obtain a string of length N such that maximum length of a palindromic substring of this string is K. Examples: Input: N = 5, K = 3 Output: "abacd" Explanation: Palindromic substrings are "a", "b", "c", "d" and "aba". Therefore, the longest palindromic substring from the given string is of length 3.
4 min read
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1
Given a string, find the longest substring which is palindrome. if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”if the given string is “abaaba”, the output should be “abaaba”if the given string is “abababa”, the output should be “abababa”if the given string is “abcbabcbabcba”, the output should be “abcbabcbabcba” We have
5 min read
Longest Non-palindromic substring
Given a string of size n. The task is to find the length of the largest substring which is not a palindrome. Examples: Input : abba Output : 3 Here maximum length non-palindromic substring is 'abb' which is of length '3'. There could be other non-palindromic sub-strings also of length three like 'bba' in this case. Input : a Output : 0 A simple sol
7 min read
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 2
In Manacher's Algorithm - Part 1, we gone through some of the basics and LPS length array. Here we will see how to calculate LPS length array efficiently. To calculate LPS array efficiently, we need to understand how LPS length for any position may relate to LPS length value of any previous already calculated position. For string “abaaba”, we see f
11 min read
Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 4
In Manacher's Algorithm Part 1 and Part 2, we gone through some of the basics, understood LPS length array and how to calculate it efficiently based on four cases. In Part 3, we implemented the same. Here we will review the four cases again and try to see it differently and implement the same. All four cases depends on LPS length value at currentLe
12 min read
Suffix Tree Application 6 - Longest Palindromic Substring
Given a string, find the longest substring which is palindrome.We have already discussed Naïve [O(n3)], quadratic [O(n2)] and linear [O(n)] approaches in Set 1, Set 2 and Manacher’s Algorithm. In this article, we will discuss another linear time approach based on suffix tree. If given string is S, then approach is following:   Reverse the string S
15+ min read
Longest Palindromic Substring
Given a string str, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first appearing substring. Examples: Input: str = "forgeeksskeegfor" Output: "geeksskeeg"Explanation: There are several possible palindromic substrings like "kssk", "ss", "eeksskee" etc. But the substring "geeksskeeg"
15+ min read
Longest substring whose any non-empty substring not prefix or suffix of given String
Given a string S of length N, the task is to find the length of the longest substring X of the string S such that: No non-empty substring of X is a prefix of S.No non-empty substring of X is a suffix of S.If no such string is possible, print −1. Examples: Input: S = "abcdefb"Output: 4Explanation: cdef is the substring satisfying the conditions. Inp
5 min read
Longest Substring of A that can be changed to Substring of B in at most T cost
Given two strings A and B of the same length and two positive integers K and T. The task is to find the longest substring of A that can be converted to the same substring at the same position in B in less than or equal to T cost. Converting any character of A to any other character costs K units. Note: If multiple valid substrings are possible then
13 min read
Longest path in a directed Acyclic graph | Dynamic Programming
Given a directed graph G with N vertices and M edges. The task is to find the length of the longest directed path in Graph.Note: Length of a directed path is the number of edges in it. Examples: Input: N = 4, M = 5 Output: 3 The directed path 1->3->2->4 Input: N = 5, M = 8 Output: 3 Simple Approach: A naive approach is to calculate the len
8 min read
Longest subsequence with a given OR value : Dynamic Programming Approach
Given an array arr[], the task is to find the longest subsequence with a given OR value M. If there is no such sub-sequence then print 0.Examples: Input: arr[] = {3, 7, 2, 3}, M = 3 Output: 3 {3, 2, 3} is the required subsequence 3 | 2 | 3 = 3Input: arr[] = {2, 2}, M = 3 Output: 0 Approach: A simple solution is to generate all the possible sub-sequ
6 min read
Make palindromic string non-palindromic by rearranging its letters
Given string str containing lowercase alphabets (a - z). The task is to print the string after rearranging some characters such that the string becomes non-palindromic. If it's impossible to make the string non-palindrome then print -1. Examples: Input: str = "abba" Output: aabb Input: str = "zzz" Output: -1 Brute Force: Iterate through all possibl
9 min read
Minimum cuts required to convert a palindromic string to a different palindromic string
Given palindromic string s, the task is to find minimum k, such that you can cut this string into k+1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. If it is impossible then print -1.Examples: Input : string = "civic" Output : 2 Explanation : ci | v | ic --> ic |
15+ min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Longest palindromic String formed using concatenation of given strings in any order
Given an array of strings arr[] of the same length, the task is to find the longest palindromic string that can be made using the concatenation of strings in any order. Examples: Input: arr[] = {"aba", "aba"} Output: abaaba Input: arr[] = {"abc", "dba", "kop", "cba", "abd"} Output: abcdbaabdcba Approach: Find all the pairs of strings which are reve
15+ min read
Maximum length palindromic substring such that it starts and ends with given char
Given a string str and a character ch, the task is to find the longest palindromic sub-string of str such that it starts and ends with the given character ch.Examples: Input: str = "lapqooqpqpl", ch = 'p' Output: 6 "pqooqp" is the maximum length palindromic sub-string that starts and ends with 'p'.Input: str = "geeksforgeeks", ch = 'k' Output: 1 "k
7 min read
Check if a substring can be Palindromic by replacing K characters for Q queries
Given a string str and Q queries in form of [L, R, K], the task is to find whether characters from the string from [L, R] with at most K changes are allowed can be rearranged to make string palindromic or not. For each query, print "YES" if it can become a palindromic string else print "NO".Examples: Input: str = "GeeksforGeeks", Q = { { 1, 5, 3 },
10 min read
Shortest Palindromic Substring
Given a string you need to find the shortest palindromic substring of the string. If there are multiple answers output the lexicographically smallest. Examples: Input: zyzz Output:y Input: abab Output: a Naive Approach: The approach is similar to finding the longest palindromic substring. We keep track of even and odd lengths substring and keep sto
8 min read
Minimum replacements such that no palindromic substring of length exceeding 1 is present in the given string
Given a string str consisting of lowercase characters, the task is to modify the string such that it does not contain any palindromic substring of length exceeding 1 by minimum replacement of characters. Examples: Input: str = �"Output: 4String can be modified to "bacbacb" by replacing 4 characters. Input: str = "geeksforgeeks"Output: 2 Approach 1:
9 min read
Minimum size substring to be removed to make a given string palindromic
Given a string S, the task is to print the string after removing the minimum size substring such that S is a palindrome or not. Examples: Input: S = "pqrstsuvwrqp"Output: pqrstsrqpExplanation:Removal of the substring "uvw" modifies S to a palindromic string. Input: S = "geeksforskeeg"Output: geeksfskeegExplanation:Removal of substring "or" modifies
15+ min read
Maximum length palindromic substring for every index such that it starts and ends at that index
Given a string S, the task for every index of the string is to find the length of the longest palindromic substring that either starts or ends at that index. Examples: Input: S = "bababa"Output: 5 5 3 3 5 5Explanation:Longest palindromic substring starting at index 0 is "babab". Therefore, length = 5Longest palindromic substring starting at index 1
15+ min read
Longest palindromic string formed by concatenation of prefix and suffix of a string
Given string str, the task is to find the longest palindromic substring formed by the concatenation of the prefix and suffix of the given string str. Examples: Input: str = "rombobinnimor" Output: rominnimor Explanation: The concatenation of string "rombob"(prefix) and "mor"(suffix) is "rombobmor" which is a palindromic string. The concatenation of
11 min read
Print Longest Palindromic Subsequence
Given a sequence, print a longest palindromic subsequence of it. Examples : Input : BBABCBCAB Output : BABCBAB The above output is the longest palindromic subsequence of given sequence. "BBBBB" and "BBCBB" are also palindromic subsequences of the given sequence, but not the longest ones. Input : GEEKSFORGEEKS Output : Output can be either EEKEE or
11 min read
three90RightbarBannerImg