![]() |
VOOZH | about |
Prerequisite:Manacher’s Algorithm
Given a string, your task is to determine the longest palindromic substring of the string. For example, the longest palindrome in aybabtu is bab.
Example:
Input: s = aybabtu
Output: babInput: GeeksgfgGeeks
Output: gfg
Approach:
The idea is to use Manacher’s algorithm, which is a linear time complexity algorithm for finding the longest palindromic substring in a given string.
Lets break down the intuition into some steps:
- We'll use two arrays, oddLength[] and evenLength[], to store the lengths of the longest odd-length and even-length palindromic substrings centered at each index of the input string.
- Odd-Length Palindromes: First calculates the longest odd-length palindromic substring centered at each index. It uses a variable length to keep track of the current length of the palindrome. It starts from the center and expands in both directions (left and right) until it finds a mismatch or reaches the boundary of the string. The left and right variables are used to keep track of the boundaries of the current longest palindrome.
- Even-Length Palindromes: The process is repeated for even-length palindromes. The only difference is that the initial length is set to 0 and the expansion starts from one position to the left of the center.
- Finding the Longest Palindrome: After the lengths of all palindromic substrings are calculated, iterates over the oddLength and evenLength arrays to find the maximum length and the center of the longest palindromic substring.
- Finally, the longest palindromic substring is extracted from the input string using the substr function and returned.
Steps-by-step approach:
Below are the implementation of the above approach:
gfg
Time Complexity: O(n), where n is the length of given string
Auxiliary Space: O(n)