![]() |
VOOZH | about |
Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first occurrence of the longest palindromic substring from left to right.
Examples:
Input: s = "aaaabbaa"
Output: "aabbaa"
Explanation: The longest palindromic substring is "aabbaa".Input: s = "geeks"
Output: "ee"Input: s = "abc"
Output: "a"
Input: s = ""
Output: ""
Approach:
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. If we know the status (i.e., palindrome or not) of the substring ranging [i, j], we can find the status of the substring ranging [i-1, j+1] by only matching the character s[i-1] and s[j+1].
- If the substring from i to j is not a palindrome, then the substring from i-1 to j+1 will also not be a palindrome. Otherwise, it will be a palindrome only if s[i-1] and s[j+1] are the same.
Based on this fact, we can create a 2D table (say dp[][] which stores status of substring s[i...j] ), and check for substrings with length from 1 to n. For each length find all the substrings starting from each character i and find if it is a palindrome or not using the above idea. The longest length for which a palindrome formed will be the required answer.
Illustration:
Follow the below illustration for a better understanding.
Consider the string "geeks". Below is the structure of the table formed and from this, we can see that the longest substring is 2.
Step by step approach:
aabbaa
Time Complexity: O(n^2)
Auxiliary Space: O(n^2)
Related Articles: