All problems

Problem 223

Shortest Palindrome

Hard · 30 pts · String, String Matching, Rolling Hash

Problem

You are given a string S. You may add characters only at the front of S, never anywhere else. Print the shortest palindrome you can create this way. The best approach keeps the longest prefix of S that is already a palindrome, and adds the reverse of the remaining suffix in front. Finding that longest palindromic prefix quickly is the hard part: build the string S + '#' + reverse(S) and use the KMP prefix function; its last value is the length of that prefix.

Input

A single string S of lowercase English letters.

Output

Print the shortest palindrome.

Constraints

1 <= |S| <= 50000

Example input

aacecaaa

Example output

aaacecaaa

Explanation

The longest palindromic prefix of "aacecaaa" is "aacecaa" (7 characters). Only the final a is left over, so adding its reverse, a, in front gives "aaacecaaa".

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Longest Common Substring Next: Count Pattern Occurrences