Shortest Palindrome Problem
Description
LeetCode Problem 214.
You are given a string s. You can convert s to a palindrome by adding characters in front of it.
Return the shortest palindrome you can find by performing this transformation.
Example 1:
Input: s = "aacecaaa"
Output: "aaacecaaa"
Example 2:
Input: s = "abcd"
Output: "dcbabcd"
Constraints:
- 0 <= s.length <= 5 * 10^4
- s consists of lowercase English letters only.
Solution
Approach: KMP Prefix Function
We may only add characters in front, so the original s stays at the end of the answer. Split s into a palindromic prefix P and the rest R. Adding reverse(R) in front gives reverse(R) + P + R, which is a palindrome. To add as little as possible, P must be the longest palindromic prefix of s.
Testing every prefix for being a palindrome takes O(n2) time. A faster test: a prefix P of s is a palindrome exactly when it equals its reverse, i.e. when P is also a suffix of reverse(s). So we need the longest prefix of s that is a suffix of reverse(s), which is what the KMP prefix function computes:
- Build
combined = s + "#" + reverse(s). - Compute
prefix[i], the length of the longest proper prefix ofcombined[0..i]that is also a suffix of it. For eachi, start fromprefix[i - 1]; while the next character does not match, fall back toprefix[length - 1]; extend by one on a match. prefixat the last position is the length ofP. Returnreverse(s)[0 .. n - |P|] + s, which isreverse(R) + s.
The "#" separator matters. Without it, a match could run across both halves: for s = "aa", "aaaa" would report a length of 3, longer than s itself.
Example: s = "aacecaaa". The longest palindromic prefix is "aacecaa", so R = "a" and the answer is "a" + "aacecaaa".
Complexity: O(n) time and O(n) space, where n is the length of s.
class Solution:
def shortestPalindrome(self, s: str) -> str:
reversed_s = s[::-1]
# The longest palindromic prefix of s is the longest prefix of s that is also a
# suffix of reversed_s. "#" keeps a match from running across the two halves.
combined = s + "#" + reversed_s
# prefix[i]: length of the longest proper prefix of combined[0..i] that is also its suffix
prefix = [0] * len(combined)
for i in range(1, len(combined)):
length = prefix[i - 1]
while length > 0 and combined[i] != combined[length]:
length = prefix[length - 1] # fall back to the next shorter border
if combined[i] == combined[length]:
length += 1
prefix[i] = length
palindrome_length = prefix[-1]
# Put the rest of s, reversed, in front.
return reversed_s[:len(s) - palindrome_length] + s
Now write it from memory
Close the write-up and solve it yourself against the tests.