Shortest Palindrome
Add the fewest characters to the front of a string to turn it into a palindrome.
Given a string s
Example 1
Output: "aaacecaaa"
Example 2
Output: "dcbabcd"
The Idea
You have probably met palindromes such as "level" or "racecar", words that read the same backwards. Here the string may not be one yet, and new characters may only go in front of it.
Take Example 2, "abcd". Writing its reverse in front always works: "dcba" + "abcd" gives "dcbaabcd". Yet the answer, "dcbabcd", is one character shorter. The "a" that starts "abcd" can be the middle of the palindrome, so only "dcb" has to be added.
Example 1 saves even more. "aacecaaa" starts with "aacecaa", which is already a palindrome on its own. Only the last "a" is left over, and copying it to the front gives "aaacecaaa". The copied part mirrors the left-over end, and the palindrome in the middle mirrors itself.
So the whole problem comes down to one question: what is the longest palindrome that ss
Write srevrev
In the row labelled s, the orange boxes hold aacecaa, the longest palindrome at the start of s
The same holds for any piece: a piece at the start of srevssrev
Solution Approach
After a look at the slow way, three things need settling: how to find the longest piece that starts srevs
Testing each start of s
What is the simplest way to find the longest palindrome at the start? Test the whole of s
Matching the start of s with the end of rev
How can one pass find the longest piece that starts srevt = s + "#" + revtt
A piece at the start of a string is called a prefix, and a piece at the end a suffix. The KMP string-matching method, named after Knuth, Morris and Pratt, computes an array usually called lps
lps[i]tii + 1ilenlenlps[i - 1]it.charAt(len)
What if the two characters differ? There is no need to start over. The next shorter match worth trying has length lps[len - 1]lpslentlps
Keeping the match inside s
Why put #srevssts#t##ss#
Building the answer
Once keepsn - keeprevkeep
Java Solution
The method shortestPalindrome
- First, reverse
with as intoStringBuilder , and glue the two intorev .t = s + "#" + rev - Create the array
, one entry per character oflps .t stays 0, because a single character has no shorter prefix. A loop then moveslps[0] from 1 to the end ofi , and for eacht ,i starts aslen .lps[i - 1] - Inside the loop, while
is above 0 andlen differs fromt.charAt(i) , fall back witht.charAt(len) . If the two characters then agree,len = lps[len - 1] grows by one. Store it inlen .lps[i] - After the loop, the last entry of
islps . Return the firstkeep characters ofs.length() - keep followed byrev .s
The main
public class ShortestPalindrome {
public static String shortestPalindrome(String s) {
String rev = new StringBuilder(s).reverse().toString();
String t = s + "#" + rev; // '#' stops a match from running across
int[] lps = new int[t.length()]; // KMP prefix function
for (int i = 1; i < t.length(); i++) {
int len = lps[i - 1];
while (len > 0 && t.charAt(i) != t.charAt(len)) {
len = lps[len - 1]; // fall back to a shorter match
}
if (t.charAt(i) == t.charAt(len)) {
len++;
}
lps[i] = len;
}
int keep = lps[t.length() - 1]; // longest palindrome that starts s
return rev.substring(0, s.length() - keep) + s;
}
public static void main(String[] args) {
String[] tests = {"aacecaaa", "abcd", "abab", "racecar", "a", ""};
for (String s : tests) {
System.out.println("\"" + s + "\" -> \"" + shortestPalindrome(s) + "\"");
}
}
}
Running it prints:
"aacecaaa" -> "aaacecaaa"
"abcd" -> "dcbabcd"
"abab" -> "babab"
"racecar" -> "racecar"
"a" -> "a"
"" -> ""
Look at the third line. "abab" starts with the palindrome "aba", so only the last "b" is copied to the front, giving "babab". "racecar" comes back unchanged: keeptkeep
The #s = "aa"t = "aaaa"lpsss.length() - keeprev.substring(0, -1)StringIndexOutOfBoundsException#tkeep
Complexity
The work is reversing sttlps
- Time: O(n), because
has 2n + 1 characters andt grows by at most one per position. Each fall-back makeslen smaller, so all the fall-backs together cannot outnumber the 2n + 1 steps of growth.len - Space: O(n), for
with n characters, andrev andt with 2n + 1 entries each.lps
The prefix function is explained step by step in