Shortest Palindrome
Hard
Topics
You are given a string s. You may convert it to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation.
Example 1
Input: s = "aacecaaa" Output: "aaacecaaa"
Example 2
Input: s = "abcd" Output: "dcbabcd"
Example 3
Input: s = "" Output: ""
Constraints
- 0 <= s.length <= 16
- s consists of lowercase English letters only.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Characters may only be added at the front, so the suffix of the result is s unchanged. That forces the structure: whatever is prepended must mirror the tail of s that is not already part of a palindrome anchored at the start.
Concretely, find the longest prefix of s that is itself a palindrome. Everything after it must be mirrored and prepended. A longer palindromic prefix means less to prepend, so the longest one gives the shortest answer.
The shown solution finds it by testing prefixes from longest to shortest, which is O(n²). The linear answer is the KMP failure function computed over s + '#' + reverse(s): its final value is exactly the length of the longest palindromic prefix, because a border of that combined string is a prefix of s that is also a suffix of its reverse.
Approach
- Scan
kfromndown to 0. - Test whether
s[0..k-1]is a palindrome with two pointers. - On the first success, return
reverse(s[k:]) + s.
Dry Run
s = "aacecaaa"
k = 8 "aacecaaa" not a palindrome
k = 7 "aacecaa" palindrome
prepend the reverse of what remains, which is "a"
answer "aaacecaaa"
"abcd" -> longest palindromic prefix is "a", prepend reverse of "bcd" -> "dcbabcd"
"a" -> already a palindrome, prepend nothing -> "a"
"" -> ""
the separator in the KMP variant matters: without the '#', s and its reverse can
overlap and the failure value can exceed len(s).Complexity
- Time — O(n²): up to
nprefix tests, each O(n). At the stated bound of 16 characters this is nothing; the real version of the problem has 5×10⁴ and needs the linear method. - Space — O(n) for the result. The KMP variant is O(n) time and O(n) space for the failure table.
Common Pitfalls
- Looking for the longest palindromic substring or suffix. It must be a prefix, because only the front may be extended.
- Scanning
kupward and returning the first palindrome found. The shortest answer comes from the longest palindromic prefix, so the scan must go downward or keep the best. - Prepending the reverse of the whole string, which always produces a palindrome and is almost never the shortest one.
- Reversing the wrong slice. What gets mirrored is
s[k:], the part after the palindromic prefix. - In the KMP variant, omitting the separator between
sand its reverse. Without it the two halves can overlap and the computed border can exceedlen(s), producing a wrong split. - Forgetting the empty string, where the answer is the empty string and the loop must still terminate cleanly at
k = 0.
Full Solution — all languages
class Solution:
def shortestPalindrome(self, s):
n = len(s)
for k in range(n, -1, -1):
ok = True
i, j = 0, k - 1
while i < j:
if s[i] != s[j]:
ok = False
break
i += 1
j -= 1
if ok:
return s[k:][::-1] + s
return simport java.util.*;
class Solution {
public String shortestPalindrome(String s) {
int n = s.length();
for (int k = n; k >= 0; k--) {
boolean ok = true;
for (int i = 0, j = k - 1; i < j; i++, j--) if (s.charAt(i) != s.charAt(j)) {
ok = false;
break;
}
if (ok) return new StringBuilder(s.substring(k)).reverse().toString() + s;
}
return s;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string shortestPalindrome(string s) {
int n = s.size();
for (int k = n; k >= 0; k--) {
bool ok = true;
for (int i = 0, j = k - 1; i < j; i++, j--) if (s[i] != s[j]) {
ok = false;
break;
}
if (ok) {
string suffix = s.substr(k);
reverse(suffix.begin(), suffix.end());
return suffix + s;
}
}
return s;
}
};/**
* @param {string} s
* @return {string}
*/ var shortestPalindrome = function(s) {
const n = s.length;
for (let k = n; k >= 0; k--) {
let ok = true;
for (let i = 0, j = k - 1; i < j; i++, j--) if (s[i] !== s[j]) {
ok = false;
break;
}
if (ok) return s.substring(k).split('').reverse().join('') + s;
}
return s;
};