Longest palindromic string possible after removal of a substring
Given a string str, the task is to find the longest palindromic string that can be obtained from it after removing a substring.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: str = “abcdefghiedcba”
Explanation: Removal of substring “fgh” leaves the remaining string palindromic
Input: str = “abba”
Explanation: Removal of substring “” as the given string is already palindromic.
- Find the longest possible pair of substrings A and B from both ends of the given string which are reverse of each other.
- Remove them from the original string.
- Find the longest palindromic substrings from both ends of the remaining string using KMP and consider the substring which is longer.
- Add the strings A and B to beginning and end of this palindromic substring respectively to get the desired output.
Below code is the implementation of the above approach:
Time complexity: O(N)
Auxiliary Space: O(N)