Shortest Palindrome - Problem
You are given a string s and your goal is to create the shortest possible palindrome by adding characters only to the beginning of the string.
A palindrome reads the same forwards and backwards (like "racecar" or "madam"). Your task is to find the minimum number of characters needed to prepend to make the entire string a palindrome.
Example: Given s = "aacecaaa", you can prepend "aaacecaa" to get "aaacecaaaacecaaa", but the optimal solution is to prepend "aa" to get "aaaacecaaa".
The key insight is finding the longest prefix of s that is also a suffix of reverse(s).
Input & Output
example_1.py โ Basic Case
$
Input:
s = "aacecaaa"
โบ
Output:
"aaacecaaa"
๐ก Note:
We need to find the shortest palindrome by prepending characters. The optimal solution prepends "aa" to get "aaacecaaa", which reads the same forwards and backwards.
example_2.py โ Single Character
$
Input:
s = "abcd"
โบ
Output:
"dcbabcd"
๐ก Note:
Since no prefix of "abcd" forms a palindrome with any suffix, we need to prepend the reverse of "bcd" which is "dcb", resulting in "dcbabcd".
example_3.py โ Already Palindrome
$
Input:
s = "racecar"
โบ
Output:
"racecar"
๐ก Note:
The string is already a palindrome, so no characters need to be prepended. The result is the original string.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Pattern
Find how much of the original already acts as a 'mirror'
2
Calculate Missing Pieces
Determine what needs to be added to complete the reflection
3
Construct Solution
Add the minimal required pieces to create perfect symmetry
Key Takeaway
๐ฏ Key Insight: Use KMP algorithm to find the optimal split point where the string overlaps with its reverse, minimizing the characters needed to prepend.
Time & Space Complexity
Time Complexity
O(n)
Single pass to build LPS array using KMP algorithm
โ Linear Growth
Space Complexity
O(n)
Space for the combined string and LPS array
โก Linearithmic Space
Constraints
- 0 โค s.length โค 5 ร 104
- s consists of lowercase English letters only
- Goal: Find the shortest possible palindrome by prepending characters
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code