To solve this problem, we need to find the shortest palindrome that can be formed by adding characters only in front of the given string s. The efficient way to achieve this is by finding the longest palindromic prefix of the string. Once we have this, we can reverse the remaining suffix and add it to the front of the original string to form the palindrome.
Here is the step-by-step solution and explanation:
class Solution:
def shortestPalindrome(self, s: str) -> str:
if not s:
return s
# Reverse the string s to compare with the original string
rev_s = s[::-1]
# Combine the original string, a separator, and the reversed string
new_s = s + '#' + rev_s
n = len(new_s)
lps = [0] * n # Longest Prefix Suffix array
# Build the LPS array using KMP algorithm's preprocessing phase
for i in range(1, n):
# Length of the previous longest prefix suffix
length = lps[i - 1]
# Adjust the length until we find a matching character or length becomes zero
while length > 0 and new_s[i] != new_s[length]:
length = lps[length - 1]
# If there's a match, increment the length
if new_s[i] == new_s[length]:
length += 1
lps[i] = length # Set the LPS value for position i
# The length of the longest palindromic prefix
pal_len = lps[-1]
# Characters to be added to the front are the suffix after the palindromic prefix, reversed
to_add = rev_s[:len(s) - pal_len]
# Form the shortest palindrome by adding the required characters in front of the original string
return to_add + s
Explanation:
-
Reverse the String:
We reverse the original string s to get rev_s. This reversed string will help us in finding palindromic prefixes by comparison.
-
Concatenate Strings with a Separator:
We create a new string new_s by concatenating the original string s, a special character '#', and the reversed string rev_s. The separator '#' is used to avoid overlap between the original and reversed strings during comparison.
-
Compute Longest Prefix Suffix (LPS) Array:
The LPS array (also known as the failure function in KMP algorithm) is computed for new_s. The LPS array at each position i stores the length of the longest proper prefix which is also a suffix for the substring new_s[0:i+1].
- We initialize the LPS array with zeros.
- For each position
i, we compare new_s[i] with new_s[length] where length is the length of the previous longest prefix suffix.
- If they match, we increment
length and set lps[i] = length.
- If they don't match, we reduce
length to lps[length - 1] and repeat the comparison until we find a match or length becomes zero.
-
Determine the Palindromic Prefix Length:
The last value in the LPS array, lps[-1], gives us the length of the longest palindromic prefix in the original string s.
-
Construct the Shortest Palindrome:
- The characters that need to be added to the front of
s are those in the suffix after the palindromic prefix. We take this suffix from the reversed string rev_s to maintain the palindromic property.
- We slice
rev_s up to len(s) - pal_len to get the required characters to add.
- Finally, we return the concatenation of
to_add and the original string s to get the shortest palindrome.
Time and Space Complexity:
- Time Complexity: O(n), where n is the length of the string
s. Building the LPS array takes linear time.
- Space Complexity: O(n), for storing the LPS array and the concatenated string
new_s.
Example Walkthrough:
Let's take s = "aacecaaa" as an example.
-
rev_s = "aaacecaa"
-
new_s = "aacecaaa#aaacecaa"
-
Compute LPS array for new_s:
LPS = [0, 1, 0, 0, 0, 1, 2, 2, 0, 1, 2, 2, 3, 4, 5, 6, 7]
-
pal_len = lps[-1] = 7 (The longest palindromic prefix has length 7)
-
Characters to add: rev_s[:len(s) - pal_len] = rev_s[:8 - 7] = "a"
-
Shortest Palindrome: to_add + s = "a" + "aacecaaa" = "aaacecaaa"