Shortest Palindrome

Strings (Advanced Algo) Advanced Problems (Less asked) Hard

Given a string s convert it into a palindrome by adding characters to the beginning of it. Return the shortest palindrome you can create by performing this transformation.

Examples:

Input: s = "aacecaaa"

Output: aaacecaaa

Explanation: Adding "a" to the front of "aacecaaa" makes it a palindrome: "aaacecaaa".

Input: s = "race"

Output: ecarace

Explanation: By adding "eca" in front of "race", the shortest palindrome "ecarace" is formed.

Input: s = "abcd"

Constraints

  • 1 <= s.length <= 104

Hints

  • "The $ separator prevents false matches across original and reversed portions. Compute the LPS (Longest Prefix Suffix) array for this new concatenated string. The LPS value at the last index gives the longest palindromic prefix of s."
  • "Take the remaining suffix (i.e., rev_s[:suffix_length]). Append it in front of s to form the shortest palindrome."

Company Tags

Wayfair Qualcomm eBay Roche Walmart Zomato Rockstar Games Philips Healthcare AMD Roblox GE Healthcare Oracle Deloitte IBM Square American Express Bungie Electronic Arts Johnson & Johnson Cloudflare Chewy Snowflake Airbnb Freshworks Optum Google Microsoft Amazon Meta Apple Netflix Adobe