![]() |
VOOZH | about |
Given a string s, find the longest substring which is a palindrome. If there are multiple answers, then find the first appearing substring.
Examples:
Input: s = "forgeeksskeegfor"
Output: "geeksskeeg"
Explanation: The longest substring that reads the same forward and backward is "geeksskeeg". Other palindromes like "kssk" or "eeksskee" are shorter.Input: s = "Geeks"
Output: "ee"
Explanation: The substring "ee" is the longest palindromic part in "Geeks". All others are shorter single characters.Input: s = "abc"
Output: "a"
Explanation: No multi-letter palindromes exist. So the first character "a" is returned as the longest palindromic substring.
Table of Content
Generate all possible substrings of the given string. For each substring, check if it is a palindrome.
If it is, update the result if its length is greater than the longest palindrome found so far.
geeksskeeg
The idea is to use Dynamic Programming to store the status of smaller substrings and use these results to check if a longer substring forms a palindrome.
Note: Refer to Longest Palindromic Substring using Dynamic Programming for detailed approach.
geeksskeeg
The idea is to traverse each character in the string and treat it as a potential center of a palindrome, trying to expand around it in both directions while checking if the expanded substring remains a palindrome.
=> For each position, we check for both odd-length palindromes (where the current character is the center) and even-length palindromes (where the current character and the next character together form the center).
=> As we expand outward from each center, we keep track of the start position and length of the longest palindrome found so far, updating these values whenever we find a longer valid palindrome.
Step-by-step approach:
geeksskeeg
The idea is to use Manacher’s algorithm, which transforms the input string by inserting separators (#) and sentinels to handle both even and odd-length palindromes uniformly.
For each position in the transformed string, we expand the longest possible palindrome centered there using mirror symmetry and previously computed values.
This expansion is bounded efficiently using the rightmost known palindrome range to avoid redundant checks.
Whenever a longer palindrome is found, we update its length and starting index in the original string.
geeksskeeg