Shortest Palindrome

Strings (Advanced Algo) Advanced Problems (Less asked) Hard
  • Fun Fact: While the exact problem may not be directly applicable in real-life, the underlying concepts behind this problem are quite important
  • They involve working with strings, understanding palindromes and an essential grip on algorithm optimization
  • For instance, within Bioinformatics, algorithms with similar concepts are used in DNA sequence alignment
  • Furthermore, palindrome detection has its significance in error detection and correction in data transmission
  • A simple use could also be seen in developing certain types of games or in palindrome date detection used in some calendar related applications!

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