Skip to content
BytePatterns

Shortest Palindrome by Prepending

HardStrings#kmp#palindrome~40m

Problem

Given a string s of lowercase letters, you may only add characters to its front. Return the shortest palindrome you can build this way. The empty string is already a palindrome, and the answer should take O(n) time.

Examples

Input:  s = "abacd"
Output: "dcabacd"
Why:    "aba" is already a palindrome at the front, so only "dc" is added
Input:  s = "race"
Output: "ecarace"
Why:    only "r" works as a palindromic front, so "eca" is added
Input:  s = ""
Output: ""
Why:    edge case, nothing to mirror

Hints

0 / 3

Stuck on the idea rather than the code? Build the KMP Table covers it.