Shortest Palindrome

Pattern: Pattern matching

hard

Adding characters only at the front, the answer keeps the longest palindromic prefix of s and puts the rest, reversed, in front. KMP on s + "#" + reverse(s) finds that prefix in O(n).

The problem

You may add characters only at the front of s. Return the shortest palindrome you can make this way. For example, "aacecaaa" gives "aaacecaaa", and "abcd" gives "dcbabcd".

The function name shortestPalindrome matches LeetCode. Use the link above for the exact statement and limits. The GFG link asks only for the number of characters added, which is n minus the palindromic prefix found here.

Think first

  • Which part of s can stay at the centre-and-right of the answer?
  • If the longest palindromic prefix of s has length k, what must you add?
  • How can a prefix-suffix search find the longest palindromic prefix?

Hints

    Brute force, and why it fails

    Try k from n down to 0 and test whether s[0..k - 1] is a palindrome: O(n²). KMP finds k in O(n).

    The key insight

    "Longest palindromic prefix" is the same as "longest prefix of s that is also a suffix of reverse(s)". That is a border question, and the KMP prefix function answers border questions directly.

    Dry run

    a0 
    b1 
    c2 
    d3 

    s = abcd. Its longest palindromic prefix is just a.

    Step 1 of 4

    The plan

    rev = reverse(s)
    t = s + "#" + rev
    lps = prefix function of t
    k = lps[len(t) - 1]
    return rev[0 .. n - k - 1] + s
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    The prefix function of a string of length 2n + 1 is linear. t and lps take O(n).

    Edge cases

    • Empty string: "".
    • Already a palindrome: unchanged.
    • One character: unchanged.
    I've built my logic, show the code

    Java

    class Solution {
        public String shortestPalindrome(String s) {
            String rev = new StringBuilder(s).reverse().toString();
            String t = s + "#" + rev;                // the longest border of t is the longest palindromic prefix of s
            int[] lps = new int[t.length()];
            for (int i = 1, len = 0; i < t.length(); ) {
                if (t.charAt(i) == t.charAt(len)) lps[i++] = ++len;
                else if (len > 0) len = lps[len - 1];
                else lps[i++] = 0;
            }
            int keep = lps[t.length() - 1];
            return rev.substring(0, s.length() - keep) + s;   // put the rest, reversed, in front
        }
    }

    C++

    class Solution {
    public:
        string shortestPalindrome(string s) {
            string rev(s.rbegin(), s.rend());
            string t = s + "#" + rev;                // the longest border of t is the longest palindromic prefix of s
            vector<int> lps(t.size(), 0);
            for (size_t i = 1, len = 0; i < t.size(); ) {
                if (t[i] == t[len]) lps[i++] = static_cast<int>(++len);
                else if (len > 0) len = lps[len - 1];
                else lps[i++] = 0;
            }
            int keep = lps.empty() ? 0 : lps.back();
            return rev.substr(0, s.size() - keep) + s;   // put the rest, reversed, in front
        }
    };

    Python

    class Solution:
        def shortestPalindrome(self, s: str) -> str:
            rev = s[::-1]
            t = s + "#" + rev                        # the longest border of t is the longest palindromic prefix of s
            lps = [0] * len(t)
            i, length = 1, 0
            while i < len(t):
                if t[i] == t[length]:
                    length += 1
                    lps[i] = length
                    i += 1
                elif length > 0:
                    length = lps[length - 1]
                else:
                    i += 1
            keep = lps[-1]
            return rev[:len(s) - keep] + s           # put the rest, reversed, in front

    Common mistakes

    • Leaving out the separator, so the border can run past s and be too long.
    • Adding the reversed rest at the end instead of the front.
    • Looking for the longest palindromic substring anywhere, not the prefix.

    Similar problems