Shortest Palindromic Superstring by Suffix–Prefix Overlap
StringsAuto-graded · 19 test casesLast updated
Tests understanding of palindromic structure by finding the minimum characters to append to a string to make the whole string a palindrome.
Shortest Palindromic Completion
Given a non-empty string s, you want to turn it into a palindrome by appending the fewest possible characters to its right end.
Return the resulting palindrome string.
How it works
A palindrome reads the same forwards and backwards. You may only add characters to the right of s — you cannot remove or change existing characters, and you cannot add anything to the left.
Find the longest prefix of s that is itself a palindrome. Everything in s after that prefix must be "mirrored" and appended on the right to complete the palindrome.
More concretely:
- Scan prefix lengths from the full string down to a single character.
- The first (longest) prefix
s[0:k]that is a palindrome tells you that the suffixs[k:]must be reversed and appended. - Append
s[k:]reversed to the end ofsand return that string.
If s itself is already a palindrome, return s unchanged (zero characters appended).
Constraints
1 <= len(s) <= 2000sconsists of lowercase English letters only (a–z).- There is always a valid answer (in the worst case, append
s[1:]reversed). - The answer is unique — there is exactly one shortest completion produced by the rule above.
Examples
Example 1
Input: shortest_palindromic_completion('racecar')
Output: 'racecar'
Example 2
Input: shortest_palindromic_completion('abcd')
Output: 'abcddcb'
Example 3
Input: shortest_palindromic_completion('aab')
Output: 'aabb'
Hints
Hint 1
Check whether the entire string is already a palindrome first — that is the best case with zero appended characters.
Hint 2
Use a helper that checks if a substring s[i:j] is a palindrome, then scan k from len(s) down to 1 to find the longest palindromic prefix.
Hint 3
Once you have the longest palindromic prefix s[0:k], the characters you need to append are the reverse of s[k:].
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key insight
We want the shortest palindrome obtainable by appending to the right of s. This is equivalent to finding the longest prefix of s that is already a palindrome and then mirroring only the leftover suffix.
Why? Suppose s = s[0:k] + s[k:] where s[0:k] is a palindrome. If we append reverse(s[k:]) on the right, we get:
s[0:k] + s[k:] + reverse(s[k:])
The right part s[k:] + reverse(s[k:]) is itself a palindrome (any string concatenated with its reverse is a palindrome). Wrapping a palindromic "core" s[0:k] with a palindromic "shell" on the right gives a full palindrome only when the core is at the left end — and that is exactly our construction. The longer the palindromic prefix we find, the fewer characters we append.
Algorithm
- Define a helper
is_palindrome(s, lo, hi)using two pointers — O(n) per call. - Iterate
kfromndown to1. The firstkfor whichs[0:k]is a palindrome is our answer. - Return
s + s[k:][::-1].
Because we start from the largest possible k, the first hit gives the longest palindromic prefix, which minimises the number of appended characters.
Correctness
- If
sis already a palindrome,k = nsucceeds immediately and we append nothing. - The loop always terminates: at worst
k = 1(any single character is a palindrome), and we appends[1:]reversed.
Complexity
- Time: O(n²) — up to n iterations, each running the O(n) palindrome check.
- Space: O(n) — for the appended result string.
For n ≤ 2 000 this is perfectly efficient.
Reference solution
def shortest_palindromic_completion(s: str) -> str:
def is_palindrome(t: str, lo: int, hi: int) -> bool:
while lo < hi:
if t[lo] != t[hi]:
return False
lo += 1
hi -= 1
return True
n = len(s)
# Find the longest palindromic prefix s[0:k]
for k in range(n, 0, -1):
if is_palindrome(s, 0, k - 1):
# Append the reverse of the remaining suffix
return s + s[k:][::-1]
# Unreachable for non-empty s, but just in case
return s + s[::-1]