Skip to content
Related Articles

Related Articles

Longest Palindromic Substring | Set 2
  • Difficulty Level : Medium
  • Last Updated : 24 Mar, 2021

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

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

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

 

Approach: Dynamic programming solution is already discussed here 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 in (n^2) time with O(1) extra space. 
 

  1. The idea is to generate all even length and odd length palindromes and keep track of the longest palindrome seen so far.
  2. To generate odd length palindrome, Fix a centre and expand in both directions for longer palindromes, i.e. fix i (index) as center and two indices as i1 = i+1 and i2 = i-1
  3. Compare i1 and i2 if equal then decrease i2 and increase i1 and find the maximum length. 
    Use a similar technique to find the even length palindrome.
  4. Take two indices i1 = i and i2 = i-1 and compare characters at i1 and i2 and find the maximum length till all pair of compared characters are equal and store the maximum length.
  5. Print the maximum length.

 

C++




// A O(n^2) time and O(1) space program to
// find the longest palindromic substring
#include <bits/stdc++.h>
using namespace std;
 
// 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)
        cout << 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)
{
    // The result (length of LPS)
    int maxLength = 1;
 
    int start = 0;
    int len = strlen(str);
 
    int low, high;
 
    // One by one consider every
    // character as center point of
    // even and length palindromes
    for (int i = 1; i < len; ++i) {
        // Find the longest even length palindrome
        // with center points as i-1 and i.
        low = i - 1;
        high = i;
        while (low >= 0 && high < len
               && str[low] == str[high]) {
            if (high - low + 1 > maxLength) {
                start = low;
                maxLength = high - low + 1;
            }
            --low;
            ++high;
        }
 
        // Find the longest odd length
        // palindrome with center point as i
        low = i - 1;
        high = i + 1;
        while (low >= 0 && high < len
               && str[low] == str[high]) {
            if (high - low + 1 > maxLength) {
                start = low;
                maxLength = high - low + 1;
            }
            --low;
            ++high;
        }
    }
 
    cout << "Longest palindrome substring is: ";
    printSubStr(str, start, start + maxLength - 1);
 
    return maxLength;
}
 
// Driver program to test above functions
int main()
{
    char str[] = "forgeeksskeegfor";
    cout << "\nLength is: "
         << longestPalSubstr(str)
         << endl;
    return 0;
}
 
// This is code is contributed by rathbhupendra

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)
{
 
    // The result (length of LPS)
    int maxLength = 1;
 
    int start = 0;
    int len = strlen(str);
 
    int low, high;
 
    // One by one consider every
    // character as center point of
    // even and length palindromes
    for (int i = 1; i < len; ++i) {
        // Find the longest even length
        // palindrome with center points
        // as i-1 and i.
        low = i - 1;
        high = i;
        while (low >= 0 && high < len
               && str[low] == str[high]) {
            if (high - low + 1 > maxLength) {
                start = low;
                maxLength = high - low + 1;
            }
            --low;
            ++high;
        }
 
        // Find the longest odd length
        // palindrome with center point as i
        low = i - 1;
        high = i + 1;
        while (low >= 0 && high < len
               && str[low] == str[high]) {
            if (high - low + 1 > maxLength) {
                start = low;
                maxLength = high - low + 1;
            }
            --low;
            ++high;
        }
    }
 
    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 {
    // A utility function to print
    // a substring str[low..high]
    static void printSubStr(String str,
                            int low, int high)
    {
        System.out.println(
            str.substring(
                low, high + 1));
    }
 
    // This function prints the
    // longest palindrome substring
    // (LPS) of str[]. It also
    // returns the length of the
    // longest palindrome
    static int longestPalSubstr(String str)
    {
        // The result (length of LPS)
        int maxLength = 1;
 
        int start = 0;
        int len = str.length();
 
        int low, high;
 
        // One by one consider every
        // character as center
        // point of even and length
        // palindromes
        for (int i = 1; i < len; ++i) {
            // Find the longest even
            // length palindrome with
            // center points as i-1 and i.
            low = i - 1;
            high = i;
            while (low >= 0 && high < len
                   && str.charAt(low)
                          == str.charAt(high)) {
                if (high - low + 1 > maxLength) {
                    start = low;
                    maxLength = high - low + 1;
                }
                --low;
                ++high;
            }
 
            // Find the longest odd length
            // palindrome with center point as i
            low = i - 1;
            high = i + 1;
            while (low >= 0 && high < len
                   && str.charAt(low)
                          == str.charAt(high)) {
                if (high - low + 1 > maxLength) {
                    start = low;
                    maxLength = high - low + 1;
                }
                --low;
                ++high;
            }
        }
 
        System.out.print("Longest palindrome substring is: ");
        printSubStr(str, start, start + maxLength - 1);
 
        return maxLength;
    }
 
    // Driver program to test above function
    public static void main(String[] args)
    {
 
        String str = "forgeeksskeegfor";
        System.out.println("Length is: " + longestPalSubstr(str));
    }
}
// This code is contributed by Sumit Ghosh

Python




# 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):
    maxLength = 1
 
    start = 0
    length = len(string)
 
    low = 0
    high = 0
 
    # One by one consider every character as center point of
    # even and length palindromes
    for i in xrange(1, length):
        # Find the longest even length palindrome with center
    # points as i-1 and i.
        low = i - 1
        high = i
        while low >= 0 and high < length and string[low] == string[high]:
            if high - low + 1 > maxLength:
                start = low
                maxLength = high - low + 1
            low -= 1
            high += 1
 
        # Find the longest odd length palindrome with center
        # point as i
        low = i - 1
        high = i + 1
        while low >= 0 and high < length and string[low] == string[high]:
            if high - low + 1 > maxLength:
                start = low
                maxLength = high - low + 1
            low -= 1
            high += 1
 
    print "Longest palindrome substring is:",
    print string[start:start + maxLength]
 
    return maxLength
 
# Driver program to test above functions
string = "forgeeksskeegfor"
print "Length is: " + str(longestPalSubstr(string))
 
# This code is contributed by BHAVYA JAIN

C#




// C# implementation of O(n^2) time
// and O(1) space method to find the
// longest palindromic substring
using System;
 
class GFG {
    // A utility function to print
    // a substring str[low..high]
    public static void printSubStr(string str,
                                   int low, int high)
    {
        Console.WriteLine(str.Substring(low,
                                        (high + 1) - low));
    }
 
    // 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 maxLength = 1; // The result (length of LPS)
 
        int start = 0;
        int len = str.Length;
 
        int low, high;
 
        // One by one consider every
        // character as center point
        // of even and length palindromes
        for (int i = 1; i < len; ++i) {
            // Find the longest even length
            // palindrome with center points
            // as i-1 and i.
            low = i - 1;
            high = i;
            while (low >= 0 && high < len && str[low] == str[high]) {
                if (high - low + 1 > maxLength) {
                    start = low;
                    maxLength = high - low + 1;
                }
                --low;
                ++high;
            }
 
            // Find the longest odd length
            // palindrome with center point as i
            low = i - 1;
            high = i + 1;
            while (low >= 0 && high < len && str[low] == str[high]) {
                if (high - low + 1 > maxLength) {
                    start = low;
                    maxLength = high - low + 1;
                }
                --low;
                ++high;
            }
        }
 
        Console.Write("Longest palindrome substring is: ");
        printSubStr(str, start, start + maxLength - 1);
 
        return maxLength;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string str = "forgeeksskeegfor";
        Console.WriteLine("Length is: " + longestPalSubstr(str));
    }
}
 
// This code is contributed by Shrikant13

PHP




<?php
// A O(n^2) time and O(1) space program to find the longest palindromic substring
  
// A utility function to print a substring str[low..high]
function printSubStr($str, $low, $high)
{
    for( $i = $low; $i <= $high; ++$i )
        echo $str[$i];
}
  
// This function prints the longest palindrome substring (LPS)
// of str[]. It also returns the length of the longest palindrome
function longestPalSubstr($str)
{
    $maxLength = 1;  // The result (length of LPS)
  
    $start = 0;
    $len = strlen($str);
  
    // One by one consider every character as center point of
    // even and length palindromes
    for ($i = 1; $i < $len; ++$i)
    {
        // Find the longest even length palindrome with center points
        // as i-1 and i. 
        $low = $i - 1;
        $high = $i;
        while ($low >= 0 && $high < $len && $str[$low] == $str[$high])
        {
            if ($high - $low + 1 > $maxLength)
            {
                $start = $low;
                $maxLength = $high - $low + 1;
            }
            --$low;
            ++$high;
        }
  
        // Find the longest odd length palindrome with center
        // point as i
        $low = $i - 1;
        $high = $i + 1;
        while ($low >= 0 && $high < $len && $str[$low] == $str[$high])
        {
            if ($high - $low + 1 > $maxLength)
            {
                $start = $low;
                $maxLength = $high - $low + 1;
            }
            --$low;
            ++$high;
        }
    }
  
    echo "Longest palindrome substring is: ";
    printSubStr($str, $start, $start + $maxLength - 1);
  
    return $maxLength;
}
  
// Driver program to test above functions
 
$str = "forgeeksskeegfor";
echo "\nLength is: ". longestPalSubstr( $str ) ;
return 0;
?>

Javascript




<script>
// Javascript implementation of O(n^2)
// time and O(1) space method
// to find the longest palindromic substring
     
    // A utility function to print
    // a substring str[low..high]
    function printSubStr(str, low, high)
    {
        document.write(str.substring(low, high + 1)+"<br>");
    }
     
    // This function prints the
    // longest palindrome substring
    // (LPS) of str[]. It also
    // returns the length of the
    // longest palindrome
    function longestPalSubstr(str)
    {
        // The result (length of LPS)
        let maxLength = 1;
        let start = 0;
        let len = str.length;
        let low, high;
         
        // One by one consider every
        // character as center
        // point of even and length
        // palindromes
        for (let i = 1; i < len; ++i)
        {
            // Find the longest even
            // length palindrome with
            // center points as i-1 and i.
            low = i - 1;
            high = i;
            while (low >= 0 && high < len
                   && str[low]
                          == str[high]) {
                if (high - low + 1 > maxLength) {
                    start = low;
                    maxLength = high - low + 1;
                }
                --low;
                ++high;
            }
  
            // Find the longest odd length
            // palindrome with center point as i
            low = i - 1;
            high = i + 1;
            while (low >= 0 && high < len
                   && str[low]
                          == str[high]) {
                if (high - low + 1 > maxLength) {
                    start = low;
                    maxLength = high - low + 1;
                }
                --low;
                ++high;
            }
        }
        document.write("Longest palindrome substring is: ");
        printSubStr(str, start, start + maxLength - 1);
        return maxLength;
    }
     
    // Driver program to test above function
    let str = "forgeeksskeegfor";
    document.write("Length is: " + longestPalSubstr(str));
     
    // This code is contributed by rag2127
</script>

Output: 
 



Longest palindrome substring is: geeksskeeg
Length is: 10

Complexity Analysis: 
 

  • Time complexity: O(n^2), where n is the length of input string. 
    Nested traversal of the string is needed. So time complexity is O(n^2).
  • Auxiliary Space: O(1). 
    No extra space is needed.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :