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 Palindromic Substring | Set 1
- Longest Non-palindromic substring
- Suffix Tree Application 6 - Longest Palindromic Substring
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 3
- 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
- Longest Palindromic Subsequence | DP-12
- Print Longest Palindromic Subsequence
- Longest substring of vowels
- Longest Common Substring | DP-29
- Longest substring with count of 1s more than 0s
- Longest substring having K distinct vowels
- Print the longest common substring