Shortest Palindrome - Problem
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.
A palindrome is a string that reads the same forward and backward.
Input & Output
Example 1 — Basic Case
$
Input:
s = "aacecaaa"
›
Output:
"aaacecaaa"
💡 Note:
The optimal palindrome is "aaacecaaa" by adding "aa" to the front. The longest palindromic prefix is "aaceca", so we add the remaining "aa" (reversed) to the front.
Example 2 — Already Palindrome
$
Input:
s = "abcd"
›
Output:
"dcbabcd"
💡 Note:
Since "abcd" has no palindromic prefix except empty string, we need to add "dcb" (reverse of "bcd") to make it "dcbabcd".
Example 3 — Single Character
$
Input:
s = "a"
›
Output:
"a"
💡 Note:
A single character is already a palindrome, so no characters need to be added.
Constraints
- 0 ≤ s.length ≤ 5 × 104
- s consists of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input String
Original string that needs to become palindrome
2
Find Prefix
Identify the longest palindromic prefix
3
Add Characters
Add minimum characters to front to form palindrome
Key Takeaway
🎯 Key Insight: Find the longest palindromic prefix, then add only the non-overlapping suffix (reversed) to minimize additions
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code