Shortest Palindrome

Add the fewest characters to the front of a string to turn it into a palindrome.

Given a string s, you may add characters only to its front. Return the shortest palindrome you can make this way. A palindrome is a string that reads the same from left to right and from right to left, such as "level".

Example 1
Input: s = "aacecaaa"
Output: "aaacecaaa"
Example 2
Input: s = "abcd"
Output: "dcbabcd"
Solution

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 s starts with? A shorter one would only leave more characters to copy. How can we find it without testing every start of s?

Write s backwards and call the result rev. Reversing moves the first seven characters of "aacecaaa", aacecaa, to the end of rev, in reverse order. Those seven form a palindrome, so reversing them changes nothing. Look at the picture below.

s = aacecaaa and rev = aaacecaa. The longest palindrome at the start of s, aacecaa, appears again at the end of rev. The left-over a of s is the first character of rev and is added in front, giving aaacecaaa.

In the row labelled s, the orange boxes hold aacecaa, the longest palindrome at the start of s, and the green box is the "a" left over. In the row labelled rev, the same aacecaa sits at the end, and the left-over "a" has moved to the front. That green "a" is exactly what gets added in front, and the answer is "aaacecaaa".

The same holds for any piece: a piece at the start of s equals the piece of the same length at the end of rev only when the piece reads the same backwards. So the longest palindrome at the start of s is the longest piece that starts s and also ends rev. That is a matching question, and a classic string-matching method answers it in one pass.

Solution Approach

After a look at the slow way, three things need settling: how to find the longest piece that starts s and ends rev, how to keep it inside s, and how to build the answer.

Testing each start of s

What is the simplest way to find the longest palindrome at the start? Test the whole of s, then drop the last character and test again, until a piece reads the same both ways. Each test compares up to half of the piece, and there can be as many tests as characters. For a string of n characters that is up to about n² / 4 comparisons, which grows fast for long strings.

Matching the start of s with the end of rev

How can one pass find the longest piece that starts s and ends rev? Glue the two into one string, t = s + "#" + rev. Now the question is about t alone: what is the longest piece that t starts with and also ends with?

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, short for "longest prefix that is also a suffix". This array is known as the prefix function.

lps[i] is the length of the longest prefix of t that also ends at position i, counting only pieces shorter than the first i + 1 characters. The array is filled from left to right. At position i, start from the match that ends at the position before, and call its length len, so len starts as lps[i - 1]. If the character at i equals the one just after that match, t.charAt(len), the match grows by one.

What if the two characters differ? There is no need to start over. The next shorter match worth trying has length lps[len - 1], then the lps of that, and so on, until one can grow or len reaches 0. For "aacecaaa", t is "aacecaaa#aaacecaa", and its last lps value is 7, the length of aacecaa.

Keeping the match inside s

Why put # between s and rev? A match must not run past the end of s, since only a piece of s can stay in place. A prefix of t longer than s includes the #, and the matching piece at the end of t would need a # in the same place. The only # sits in the middle, so the match stays within s. Any character that never appears in s does the job, and # works for strings of letters such as the examples.

Building the answer

Once keep, the length of that palindrome, is known, what goes in front? The characters of s after that palindrome, reversed. They are the first n - keep characters of rev. For "abcd", keep is 1, so the first three characters of "dcba", "dcb", go in front of "abcd".

Java Solution

The method shortestPalindrome works in these steps:

  1. First, reverse s with a StringBuilder into rev, and glue the two into t = s + "#" + rev.
  2. Create the array lps, one entry per character of t. lps[0] stays 0, because a single character has no shorter prefix. A loop then moves i from 1 to the end of t, and for each i, len starts as lps[i - 1].
  3. Inside the loop, while len is above 0 and t.charAt(i) differs from t.charAt(len), fall back with len = lps[len - 1]. If the two characters then agree, len grows by one. Store it in lps[i].
  4. After the loop, the last entry of lps is keep. Return the first s.length() - keep characters of rev followed by s.

The main method runs both examples, then "abab", "racecar", which is already a palindrome, a single letter, and the empty string.

Java
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:

Output
"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: keep is 7, the whole string, so nothing is added. The same holds for "a". For the empty string, t is just "#", keep is 0, and the answer is empty too.

The # is not decoration. Without it, s = "aa" gives t = "aaaa", whose last lps value is 3, longer than s itself. Then s.length() - keep is -1, and rev.substring(0, -1) throws a StringIndexOutOfBoundsException. With the #, t is "aa#aa" and keep is 2.

Complexity

The work is reversing s, building t, and one pass over t that fills lps.

  • Time: O(n), because t has 2n + 1 characters and len grows by at most one per position. Each fall-back makes len smaller, so all the fall-backs together cannot outnumber the 2n + 1 steps of growth.
  • Space: O(n), for rev with n characters, and t and lps with 2n + 1 entries each.

The prefix function is explained step by step in KMP String Matching.