Shortest Palindrome

Hard Arrays & Hashing String Matching (KMP)

Shortest Palindrome is a hard arrays & hashing problem solved with the string matching (kmp) pattern. The best approach, optimal (kmp prefix function on s + '#' + reverse), runs in O(n) time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (check every prefix) up.

Problem

You are given a string s. You may add characters to it, but only in front of it: the letters of s must stay where they are, at the end of the result.

Return the shortest palindrome you can build this way. A palindrome is a string that reads the same from left to right and from right to left.

If s is already a palindrome, return it as it is. The empty string counts as a palindrome.

Examples

Example 1

Input
s = "abacd"
Output
"dcabacd"
Why
The longest prefix of s that reads the same both ways is "aba". The part after it, "cd", has to be mirrored in front, so we add "dc" and get "dcabacd".

Example 2

Input
s = "aabba"
Output
"abbaabba"
Why
"aabba" and "aabb" and "aab" are not palindromes, but "aa" is. The leftover "bba" is reversed to "abb" and added in front.

Example 3

Input
s = "racecar"
Output
"racecar"
Why
s is already a palindrome, so nothing needs to be added.

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s consists of lowercase English letters only.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (check every prefix)O(n²)O(n)
Optimal (KMP prefix function on s + '#' + reverse)O(n)O(n)

1Brute force (check every prefix)

TimeO(n²)Up to n prefixes are checked, and each check can compare up to n / 2 pairs before it fails.
SpaceO(n)The check itself uses two indexes; building the answer needs O(n) for the new string.

The answer always ends with s itself, and only letters in front are added. If the first k letters of s already form a palindrome, putting the reverse of the remaining letters in front closes the mirror: reverse(s[k..]) + s reads the same both ways. Fewer added letters means a longer palindromic prefix, so try prefix lengths from n downwards and stop at the first one that is a palindrome. A one-letter prefix always is, so the search always ends.

  1. For end = n down to 1: check whether s[0..end) is a palindrome with two pointers moving inwards.
  2. At the first end that works, return reverse(s[end..]) + s.
  3. If s is empty, return s.
class Solution {
    public String shortestPalindrome(String s) {
        int n = s.length();
        for (int end = n; end > 0; end--) {
            if (isPalindrome(s, end)) {
                String rest = s.substring(end);
                return new StringBuilder(rest).reverse().toString() + s;
            }
        }
        return s;
    }

    private boolean isPalindrome(String s, int end) {
        int i = 0, j = end - 1;
        while (i < j) {
            if (s.charAt(i) != s.charAt(j)) return false;
            i++;
            j--;
        }
        return true;
    }
}

2Optimal (KMP prefix function on s + '#' + reverse)

TimeO(n)t has 2n + 1 letters. k goes up by at most one per step and every fall-back lowers it, so the total work of the while loop over the whole run is at most 2n + 1.
SpaceO(n)The strings rev and t and the lps array each hold O(n) values.

Let rev be s reversed. A prefix of s of length k is a palindrome exactly when it equals the last k letters of rev, because those letters are the same prefix read backwards. So we want the longest prefix of s that is also a suffix of rev. Glue them as t = s + '#' + rev and compute the KMP prefix function lps, where lps[i] is the length of the longest proper prefix of t[0..i] that is also a suffix of it. The '#' never matches a letter, so a match can never cross from s into rev and its length stays at most n. The last value, keep = lps[t.length - 1], is the longest palindromic prefix; the letters still missing are the first n - keep letters of rev.

  1. Build rev = reverse(s) and t = s + '#' + rev.
  2. Compute lps over t: keep a length k; for each i from 1, while k > 0 and t[i] != t[k], fall back with k = lps[k - 1]; if t[i] == t[k], k++; store lps[i] = k.
  3. keep = lps[t.length - 1] is the length of the longest palindromic prefix of s.
  4. Return rev.substring(0, n - keep) + s.
class Solution {
    public String shortestPalindrome(String s) {
        String rev = new StringBuilder(s).reverse().toString();
        String t = s + "#" + rev;
        int[] lps = new int[t.length()];
        for (int i = 1, k = 0; i < t.length(); i++) {
            while (k > 0 && t.charAt(i) != t.charAt(k)) k = lps[k - 1];
            if (t.charAt(i) == t.charAt(k)) k++;
            lps[i] = k;
        }
        int keep = lps[t.length() - 1];
        return rev.substring(0, s.length() - keep) + s;
    }
}

Edge cases to test

  • The empty string: the answer is the empty string
  • A single letter, or a string that is already a palindrome: return s unchanged
  • Only the first letter is a palindromic prefix ("abcd"): almost the whole string is reversed in front
  • All letters equal ("aaaa"): already a palindrome
  • Building s + rev(s) without a separator lets the prefix-suffix match run longer than s ("aa" gives 3), so a separator that is not a letter is needed
  • A long run of one letter with a single different letter inside, which makes checking every prefix slow

Hints

Hint 1

Whatever you add in front, the original s ends the answer. So the answer is some string w, then s. Which part of s can be left as it is?

Hint 2

If the prefix s[0..k) is a palindrome, then reverse(s[k..]) + s is a palindrome. To make the answer short, find the longest palindromic prefix.

Hint 3

A prefix of s is a palindrome exactly when it equals a suffix of reverse(s). The longest prefix of s + "#" + reverse(s) that is also its suffix gives that length in linear time (the KMP prefix function).

FAQ

What is the best time complexity for Shortest Palindrome?

Optimal (KMP prefix function on s + '#' + reverse) runs in O(n) time and O(n) extra space. t has 2n + 1 letters. k goes up by at most one per step and every fall-back lowers it, so the total work of the while loop over the whole run is at most 2n + 1.

Which pattern does Shortest Palindrome use?

It is a arrays & hashing problem that uses the string matching (kmp) pattern. Other problems with the same pattern: Longest Happy Prefix, Find the Index of the First Occurrence in a String.

Is there a brute force solution for Shortest Palindrome?

Yes. Brute force (check every prefix) takes O(n²) time and O(n) space. The answer always ends with s itself, and only letters in front are added.

Which edge cases should I test for Shortest Palindrome?

The empty string: the answer is the empty string; A single letter, or a string that is already a palindrome: return s unchanged; Only the first letter is a palindromic prefix ("abcd"): almost the whole string is reversed in front; All letters equal ("aaaa"): already a palindrome; Building s + rev(s) without a separator lets the prefix-suffix match run longer than s ("aa" gives 3), so a separator that is not a letter is needed; A long run of one letter with a single different letter inside, which makes checking every prefix slow.