KatInterview

Minimum Prefix Extension to Form a Palindrome

StringsAuto-graded · 18 test cases
HardAuto-gradedStringsstringskmppalindrome

Last updated

Tests whether you can use the KMP failure function to find the longest palindromic prefix of a string and prepend the minimum number of characters to make it a palindrome.

Problem

You are given a string s. Your only allowed operation is to insert zero or more characters at the very beginning of s.

Return the shortest string that can be produced by this operation such that the result is a palindrome.

How to Think About It

Because you can only add characters to the front, whatever you add must "mirror" some tail of s. To keep the result as short as possible, you want to leave the longest possible portion of s intact — specifically, the longest prefix of s that is already a palindrome. The characters in s that lie beyond that palindromic prefix must then be reversed and prepended.

For example, if s = "aacecaaa", the longest palindromic prefix is "aacecaa" (length 7). The leftover suffix is "a", so you prepend "a" reversed — still "a" — to get "aaacecaaa".

Constraints

  • 0 <= len(s) <= 5 * 10^4
  • s contains only lowercase English letters.

Examples

Example 1

Input: make_shortest_palindrome('aacecaaa')

Output: 'aaacecaaa'

Example 2

Input: make_shortest_palindrome('abcd')

Output: 'dcbabcd'

Hints

Hint 1

Think about what structure allows you to add as few characters as possible to the front: which prefix of s could you leave completely unchanged?

Hint 2

Build a new string by concatenating s, a separator character that does not appear in s, and the reverse of s. The KMP failure function applied to this concatenation reveals the answer in its final value.

Hint 3

The last entry of the KMP prefix (failure) array for the concatenated string gives the length of the longest palindromic prefix of s. Use that length to slice and reverse the remainder, then prepend it.