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
Shortest Palindrome: Transform "aacecaaa" → "aaacecaaa"Goal: Add minimum characters to front to make palindromeStep 1: Input StringaacecaaaStep 2: Find Palindromic Prefixaacecaaa← remainingStep 3: Add Remaining Reversedaa+aacecaaa= "aaacecaaa"
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
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
89.4K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen