Given a string, find the longest substring which is palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”.
We have discussed dynamic programming solution 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.
Step to generate odd length palindrome:
Fix a centre and expand in both directions for longer palindromes.
Step to generate even length palindrome
Fix two centre ( low and high ) and expand in both directions for longer palindromes.
Longest palindrome substring is: geeksskeeg Length is: 10
Time complexity: O ( n^2 ) where n is the length of input string.
Auxiliary Space: O ( 1 )
We will soon be adding more optimized method as separate post.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Longest Palindromic Substring using Palindromic Tree | Set 3
- Longest Non-palindromic substring
- Longest Palindromic Substring | Set 1
- Suffix Tree Application 6 - Longest Palindromic Substring
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 2
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 4
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 3
- Maximum length palindromic substring such that it starts and ends with given char
- Longest Palindromic Subsequence | DP-12
- Print Longest Palindromic Subsequence
- Longest substring with count of 1s more than 0s
- Longest Common Substring | DP-29
- Longest substring of vowels
- Print the longest common substring