TRT
Sign in
hardAdvancedLeetCode#prefix function on s + # + reverse(s)

Shortest palindrome

Add the fewest characters to the front of a string to make it a palindrome, by finding its longest palindromic prefix with the prefix function.

The Runtime Theory Team1 min read
Taught inKMP and prefix functionsPro — members onlyThe prefix function records, for every position of a pattern, the longest proper prefix that is also a suffix there. Knuth-Morris-Pratt uses it to search a text without ever moving backward, in O(n + m) time in the worst case.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

ins = "aacecaaa"

out"aaacecaaa"

ins = "abcd"

out"dcbabcd"

ins = "a"

out"a"

ins = ""

out""

You may add characters only in front of s. Return the shortest palindrome you can make this way.

Before you code

The part of s that can stay unmatched is its longest palindromic prefix. A palindromic prefix of s equals a suffix of reverse(s). Which string's longest border is exactly that?

Hints

  1. Build t = s + "#" + reverse(s). The separator stops a border from crossing into the middle.
  2. The last value of t's prefix function is the length k of the longest palindromic prefix of s.
  3. Return reverse(s[k:]) + s. That is O(n), against O(n²) for checking every prefix.

Production & complexity notes

When solving Shortest palindrome on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in KMP and prefix functions to reinforce the underlying pattern.

What it practices

Turning a palindrome question into a border question, from KMP and prefix functions.

Not started

Sign in to save your learning progress.

Sign in to save