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
Visualization
Time & Space Complexity
Single pass to build LPS array using KMP algorithm
Space for the combined string and LPS array
Constraints
- 0 โค s.length โค 5 ร 104
- s consists of lowercase English letters only
- Goal: Find the shortest possible palindrome by prepending characters