Shortest Palindrome
Master this topic with zero to advance depth.
Shortest Palindrome
You are given a string s. You can convert s to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.
Examples
Add 'a' to the front to get 'aaacecaaa', which is a palindrome.
Add 'dcb' to the front to get 'dcbabcd'.
Level I: Brute Force (Prefix Check)
Intuition
The problem asks for the shortest palindrome created by adding chars to the front. This means we are effectively looking for the longest prefix of s that is already a palindrome.
Iterate through the string from the end. For each index i, check if s[0...i] is a palindrome. If it is, then the substring s[i+1...n-1] must be reversed and prepended to s.
Detailed Dry Run
s = "abcd" â prefix "abcd" is NOT â prefix "abc" is NOT â prefix "ab" is NOT â prefix "a" IS. Reverse "bcd" â "dcb". Result: "dcbabcd".
â ī¸ Common Pitfalls & Tips
Inefficient for large N (O(N^2) due to substring/startswith checks inside a loop).
Level II: Better (Two Pointers Recursion)
Intuition
We can use two pointers to find the largest prefix that could be a palindrome. We match characters from the beginning and end. If they match, we move both. If not, we skip the end character. Finally, we recurse on the unmatched middle part.
Detailed Dry Run
s="aacecaaa". i=0, j=7. s[0]==s[7]... Match up to some point. Recurse.
â ī¸ Common Pitfalls & Tips
O(N^2) in worst case (e.g., "aaaaa...ab"). Recursion depth can be an issue.
Level III: Optimal (KMP Longest Prefix Function)
Intuition
We can use the KMP pattern matching logic (next array or lps array) to find the longest prefix that is a palindrome in O(N) time. We construct a temporary string T = s + "#" + reverse(s).
In the string s + "#" + rev(s), the last value of the KMP lookup table gives the length of the longest prefix of s that matches a suffix of rev(s), which is exactly the longest palindromic prefix.
Detailed Dry Run
s="aacecaaa", rev="aaacecaa". T="aacecaaa#aaacecaa". LPS[last] = 7. Prefix length 7 ("aacecaa") is palindrome. Prep rev[0...8-7] = "a". Result: "aaacecaaa".
â ī¸ Common Pitfalls & Tips
The separator '#' is necessary to ensure the prefix search doesn't cross the boundary into the reversed portion.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.