Minimum Prefix Extension to Form a Palindrome
StringsAuto-graded · 18 test casesLast updated
Tests whether you can use the KMP failure function to find the longest palindromic prefix of a string and prepend the minimum number of characters to make it a palindrome.
Problem
You are given a string s. Your only allowed operation is to insert zero or more characters at the very beginning of s.
Return the shortest string that can be produced by this operation such that the result is a palindrome.
How to Think About It
Because you can only add characters to the front, whatever you add must "mirror" some tail of s. To keep the result as short as possible, you want to leave the longest possible portion of s intact — specifically, the longest prefix of s that is already a palindrome. The characters in s that lie beyond that palindromic prefix must then be reversed and prepended.
For example, if s = "aacecaaa", the longest palindromic prefix is "aacecaa" (length 7). The leftover suffix is "a", so you prepend "a" reversed — still "a" — to get "aaacecaaa".
Constraints
0 <= len(s) <= 5 * 10^4scontains only lowercase English letters.
Examples
Example 1
Input: make_shortest_palindrome('aacecaaa')
Output: 'aaacecaaa'
Example 2
Input: make_shortest_palindrome('abcd')
Output: 'dcbabcd'
Hints
Hint 1
Think about what structure allows you to add as few characters as possible to the front: which prefix of s could you leave completely unchanged?
Hint 2
Build a new string by concatenating s, a separator character that does not appear in s, and the reverse of s. The KMP failure function applied to this concatenation reveals the answer in its final value.
Hint 3
The last entry of the KMP prefix (failure) array for the concatenated string gives the length of the longest palindromic prefix of s. Use that length to slice and reverse the remainder, then prepend it.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core observation
We can only add characters to the front of s. Any valid prepended string must be the reverse of some suffix of s (otherwise the result could not be a palindrome). To minimise the number of characters added, we want that suffix to be as short as possible — equivalently, we want the longest prefix of s that is already a palindrome. Call its length L. Then:
s[:L]is a palindrome and stays in place.s[L:]is the leftover suffix; reversing it and prepending givesreverse(s[L:]) + s.- That result is a palindrome of length
n + (n - L), which is minimal.
Finding L efficiently with KMP
Scanning every prefix to check whether it is a palindrome costs O(n²) in the worst case (e.g. "aaaa…ab"). The KMP failure function lets us do it in O(n).
- Form the concatenated sequence
t = s + [sentinel] + reverse(s). The sentinel is any value that does not appear ins(usingNonein a list works cleanly). - Compute the standard KMP prefix (failure) array for
t. Entryprefix[i]is the length of the longest proper prefix oft[0..i]that is also a suffix oft[0..i]. - A prefix of
tis a prefix ofs. A suffix oftis a suffix ofreverse(s), which corresponds to a prefix ofsread backwards. A prefix equals its own reverse exactly when it is a palindrome. Soprefix[-1]is the length of the longest palindromic prefix ofs. - The sentinel guarantees no match ever spans the boundary, so
prefix[-1] ≤ len(s).
Why the result is correct
- Lower bound. Any palindrome formed by prepending characters to
smust contain a palindromic prefix ofsas its "inner mirror". The minimum number of characters added is thereforen − L_max. - Achievable.
reverse(s[L:]) + s[:L] + s[L:]is a palindrome:s[:L]is already symmetric, andreverse(s[L:])mirrorss[L:]across the full string's center.
Complexity
- Time: O(n). The KMP computation runs in O(|t|) = O(2n + 1) = O(n).
- Space: O(n) for the sequence
tand theprefixarray.
Edge cases
| Input | Behaviour |
|---|---|
"" | L = 0, nothing is prepended, returns "". |
Already a palindrome ("aba") | L = n, nothing is prepended. |
| Single character | L = 1 = n, returned unchanged. |
All distinct ("abcd") | L = 1, returns "dcb" + "abcd". |
Repetitive + one mismatch ("aaab") | L = 1, O(n) KMP handles this fast; a naïve check would be slow. |
Reference solution
def make_shortest_palindrome(s: str) -> str:
# Build the KMP search string: s + sentinel + reverse(s).
# The sentinel (None) guarantees no match crosses the boundary,
# so the failure function value stays bounded by len(s).
seq = list(s) + [None] + list(reversed(s))
prefix = [0] * len(seq)
for i in range(1, len(seq)):
j = prefix[i - 1]
while j and seq[i] != seq[j]:
j = prefix[j - 1]
if seq[i] == seq[j]:
j += 1
prefix[i] = j
# prefix[-1] is the length of the longest palindromic prefix of s.
longest_palindromic_prefix = prefix[-1]
# Reverse the suffix that falls outside the palindromic prefix and prepend it.
return s[longest_palindromic_prefix:][::-1] + s