![]() |
VOOZH | about |
Given a string s consisting of only lowercase English letters, find the minimum number of characters that need to be added to the front of s to make it a palindrome.
Note: A palindrome is a string that reads the same forward and backward.
Examples:
Input: s = "abc"
Output: 2
Explanation: We can make above string palindrome as "cbabc", by adding 'b' and 'c' at front.Input: s = "aacecaaaa"
Output: 2
Explanation: We can make above string palindrome as "aaaacecaaaa" by adding two a's at front of string.
Table of Content
The idea is based on the observation that we need to find the longest prefix from given string which is also a palindrome. Then minimum front characters to be added to make given string palindrome will be the remaining characters.
2
The key observation is that the longest palindromic prefix of a string becomes the longest palindromic suffix of its reverse.
Given a string s = "aacecaaaa", its reverse revS = "aaaacecaa". The longest palindromic prefix of s is "aacecaa".
To find this efficiently, we use the LPS array from the KMP algorithm. We concatenate the original string with a special character and its reverse: s + '$' + revS.
The LPS array for this combined string helps identify the longest prefix of s that matches a suffix of revS, which also represents the palindromic prefix of s.
The last value of the LPS array tells us how many characters already form a palindrome at the beginning. Thus, the minimum number of characters to add to make s a palindrome is s.length() - lps.back().
2
The idea is to use Manacher’s algorithm to efficiently find all palindromic substrings in linear time.
We transform the string by inserting special characters (#) to handle both even and odd length palindromes uniformly.
After preprocessing, we scan from the end of the original string and use the palindrome radius array to check if the prefix s[0...i] is a palindrome. The first such index i gives us the longest palindromic prefix, and we return n - (i + 1) as the minimum characters to add.
2
Time Complexity: O(n), manacher's algorithm runs in linear time by expanding palindromes at each center without revisiting characters, and the prefix check loop performs O(1) operations per character over n characters.
Auxiliary Space: O(n), used for the modified string and the palindrome length array p[], both of which grow linearly with the input size.