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 - KMP Algorithm INPUT String s: a a c e c a a a 0 1 2 3 4 5 6 7 Find longest palindrome starting at index 0 Longest Palindrome Prefix: "aacecaa" (7 chars) Remaining to prepend: "a" (reversed) Input: s = "aacecaaa" ALGORITHM STEPS 1 Create combined string s + "#" + reverse(s) "aacecaaa#aaacecaa" 2 Build KMP failure table LPS array for combined LPS[16] = 7 (key value) [0,1,0,0,0,1,2,0,0,1,2,3,4,5,6,7] 3 Find longest prefix LPS[last] = palindrome len Palindrome prefix length = 7 "aacecaa" is palindrome 4 Build result Prepend reverse of suffix reverse(s[7:]) + s "a" + "aacecaaa" FINAL RESULT Shortest Palindrome: a a a c e c a a a added original string Palindrome Verification Forward: aaacecaaa Backward: aaacecaaa OK - Same! Output: "aaacecaaa" Statistics Original length: 8 Result length: 9 Added: 1 character Key Insight: The KMP failure function finds the longest proper prefix that is also a suffix. By creating s + "#" + reverse(s), the LPS value at the end gives us the longest palindrome prefix of s. Time Complexity: O(n) | Space Complexity: O(n) - Linear solution using string matching! TutorialsPoint - Shortest Palindrome | KMP Algorithm Approach
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