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
๐Ÿชž Mirror Construction ProcessStep 1: Original String Analysisa a c e c a a aFind existing symmetryStep 2: Add Missing Mirror Piecesa aa a c e c a a aPrepend minimum required charactersโœ“ Perfect Palindromea a a c e c a a a
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

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Space for the combined string and LPS array

n
2n
โšก Linearithmic Space

Constraints

  • 0 โ‰ค s.length โ‰ค 5 ร— 104
  • s consists of lowercase English letters only
  • Goal: Find the shortest possible palindrome by prepending characters
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 22
58.0K Views
Medium-High Frequency
~35 min Avg. Time
1.5K 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