Shortest Palindrome (LeetCode 214): Solution and Explanation

Hard
String
Rolling Hash
String Matching
Hash Function

You may only add characters to the front of a string s. Return the shortest palindrome you can make this way. The answer always exists, since prepending the full reverse of s works, but usually far fewer characters are needed.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Whatever we prepend, the original s ends up as the right part of the palindrome. If s begins with a palindrome of length L, we can leave that block in the middle and only mirror the rest: take the remaining suffix s[L:], reverse it and put it in front. The longer that palindromic prefix, the fewer characters we add. So the whole problem reduces to finding the longest prefix of s that is a palindrome.

The brute force checks each prefix length from n down to 1 and stops at the first palindrome, which is O(n²) in the worst case (think of a string like "aaaaaaab" with a long run). We want to answer the question in linear time.

A prefix of s is a palindrome exactly when it equals the matching suffix of reverse(s). So we need the longest prefix of s that is also a suffix of reverse(s). That is precisely what the KMP failure function computes: for each position, the length of the longest proper prefix that is also a suffix. Build the string s + '#' + reverse(s) and compute the failure table. The final value is the length we want. The # separator, a character that never appears in s, prevents a match from spilling across the boundary and claiming a prefix longer than s itself.

Approach: KMP failure function

  1. Compute rev = s[::-1] and build combined = s + '#' + rev.
  2. Create a failure array fail of the same length, with fail[0] = 0.
  3. For each index i from 1, start from j = fail[i - 1] and fall back with j = fail[j - 1] while j > 0 and combined[i] != combined[j].
  4. If combined[i] == combined[j], extend the match with j += 1, then store fail[i] = j.
  5. fail[-1] is the length of the longest palindromic prefix of s.
  6. Return rev[:len(s) - fail[-1]] + s, which prepends the reversed leftover suffix.

Step-by-step example

s = "abac"
  1. rev is "caba" and combined is "abac#caba".
  2. Over the first part, the table is [0, 0, 1, 0, 0]: the second "a" at index 2 matches the prefix "a", while "c" and "#" reset it.
  3. Index 5 is "c", which does not match combined[0] = "a", so fail[5] = 0.
  4. Index 6 is "a", matching "a" (length 1). Index 7 is "b", extending to "ab" (length 2). Index 8 is "a", extending to "aba" (length 3).
  5. fail[-1] = 3, so the longest palindromic prefix is "aba". We add rev[:4 - 3], which is "c".
  6. The answer is "c" + "abac" = "cabac".

Code: Python, Java, C++

1class Solution:
2    def shortestPalindrome(self, s: str) -> str:
3        # Use KMP failure function to find longest palindrome prefix
4        rev = s[::-1]
5        combined = s + '#' + rev
6
7        # Build KMP failure table
8        n = len(combined)
9        fail = [0] * n
10        for i in range(1, n):
11            j = fail[i - 1]
12            while j > 0 and combined[i] != combined[j]:
13                j = fail[j - 1]
14            if combined[i] == combined[j]:
15                j += 1
16            fail[i] = j
17
18        # fail[-1] is length of longest palindrome prefix
19        return rev[:len(s) - fail[-1]] + s

Time and space complexity

Time

O(n)

The combined string has length 2n + 1. KMP's fallback loop is amortized: j rises by at most one per step and every fallback lowers it, so the total work is linear.

Space

O(n)

We store the reversed string, the combined string and the failure array, each of length O(n).

Other approaches

Check prefixes from longest to shortest (time O(n²), space O(n))

For L from n down to 1, test whether s[:L] is a palindrome and stop at the first hit. It is short and passes many test sets, but strings with long runs of one character push it to quadratic time.

Rolling hash (time O(n), space O(1))

Scan s once while keeping a forward hash and a reverse hash of the current prefix. Whenever they match, record that prefix length as a palindrome. It is also linear but can produce false positives on hash collisions unless you verify the final candidate.

Common mistakes

  • Leaving out the # separator. Without it, a string like "aaa" yields a failure value larger than n, and the slice becomes wrong.
  • Reading the maximum of the whole failure array instead of fail[-1]. Only the last value describes a suffix of the reversed string.
  • Prepending the reverse of the palindromic prefix instead of the reverse of the leftover suffix.
  • Using if instead of while for the fallback, which skips valid shorter borders and gives wrong lengths.

Frequently asked questions

Why does KMP find the longest palindromic prefix?

A prefix of s is a palindrome exactly when it reads the same as the matching suffix of reverse(s). The failure function at the end of s + '#' + reverse(s) gives the longest prefix that is also a suffix, which is that palindrome length.

What does the # character do in the shortest palindrome trick?

It acts as a wall so that a border cannot extend from the first half into the second. Any character that cannot occur in s works.

Can you solve Shortest Palindrome with two pointers?

There is a recursive two-pointer method that narrows down the palindromic prefix and recurses on the rest. It is accepted in practice but its worst case is O(n²), so KMP is the safer linear solution.