Shortest Palindrome

Hard

Topics
StringRolling HashString Matching

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

a0a1c2e3c4a5a6a7
Input:  s = "aacecaaa"
Output: "aaacecaaa"

Example 2

a0b1c2d3
Input:  s = "abcd"
Output: "dcbabcd"

Example 3

empty array
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

  1. Scan k from n down to 0.
  2. Test whether s[0..k-1] is a palindrome with two pointers.
  3. 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 n prefix 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 k upward 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 s and its reverse. Without it the two halves can overlap and the computed border can exceed len(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 s
Asked at Accenture
SensAI
Beta
Tap the mic to stop voice mode