# Longest Palindromic Substring | Set 2

• Difficulty Level : Medium
• Last Updated : 24 Nov, 2021

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".```

Become a success story instead of just reading about them. Prepare for coding interviews at Amazon and other top product-based companies with our Amazon Test Series. Includes topic-wise practice questions on all important DSA topics along with 10 practice contests of 2 hours each. Designed by industry experts that will surely help you practice and sharpen your programming skills. Wait no more, start your preparation today!

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.

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 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
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 pairs 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 ``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(``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 palindrome 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 palindrome 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<

## C

 `// A O(n^2) time and O(1) space``// program to find the longest``// palindromic substring``#include ``#include ` `// 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]) {``            ``--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 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)) {``                ``--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 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]:``            ``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 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]) {``                ``--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

 `= 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

 ``

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.