Longest Palindromic Substring | Set 2
Given a string, find the longest substring which is a palindrome.
For Example:
Input: Given string :"forgeeksskeegfor", Output: "geeksskeeg". Input: Given string :"Geeks", Output: "ee".
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
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 in (n^2) time with O(1) extra space.
- The idea is to generate all even length and odd length palindromes and keep track of the longest palindrome seen so far.
- To generate odd length palindrome, Fix a center and expand in both directions for longer palindromes, i.e. fix i (index) as the center and two indices as i1 = i+1 and i2 = i-1
- 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. - Take two indices i1 = i and i2 = i-1 and compare characters at i1 and i2 and find the maximum length till all pairs of compared characters are equal and store the maximum length.
- 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]// This function prints the// longest palindrome substring (LPS)// of str[]. It also returns the// length of the longest palindromeint 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]) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str[low] == str[high] && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } // 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]) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str[low] == str[high] && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } } cout << "Longest palindrome substring is: "; int ans=maxlength; while(ans--) cout<<str[start++]; return maxLength;}// Driver program to test above functionsint 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 palindromeint 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]) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str[low] == str[high] && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } // 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]) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str[low] == str[high] && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } } printf("Longest palindrome substring is: "); printSubStr(str, start, start + maxLength - 1); return maxLength;}// Driver program to test above functionsint 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 substringpublic 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)) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } // 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)) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } } 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 palindromedef 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]: low -= 1 high += 1 # Move back to the last possible valid palindrom substring # as that will anyway be the longest from above loop low += 1 high -= 1 if string[low] == string[high] and high - low + 1 > maxLength: start = low maxLength = high - low + 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]: low -= 1 high += 1 # Move back to the last possible valid palindrom substring # as that will anyway be the longest from above loop low += 1 high -= 1 if string[low] == string[high] and high - low + 1 > maxLength: start = low maxLength = high - low + 1 print "Longest palindrome substring is:", print string[start:start + maxLength] return maxLength# Driver program to test above functionsstring = "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 substringusing 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]) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str[low] == str[high] && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } // 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]) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str[low] == str[high] && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } } 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 palindromefunction 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]) { --$low; ++$high; } ++$low; --$high; if ($str[$low] == $str[$high] && $high - $low + 1 > $maxLength) { $start = $low; $maxLength = $high - $low + 1; } // 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]) { --$low; ++$high; } ++$low; --$high; if ($str[$low] == $str[$high] && $high - $low + 1 > $maxLength) { $start = $low; $maxLength = $high - $low + 1; } } 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]) { --low; ++high; } ++low; --high; if (str[low] == str[high] && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } // 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]) { --low; ++high; } ++low; --high; if (str[low] == str[high] && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } } 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 the input string.
A 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 have more information about the topic discussed above.



