Shortest Palindrome - Complete Solution Guide
Shortest Palindrome is LeetCode problem 214, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
You are given a string s . You can convert s to a palindrome by adding characters in front of it. Return the shortest palindrome you can find by performing this transformation . Example 1: Input: s = "aacecaaa" Output: "aaacecaaa" Example 2: Input: s = "abcd" Output: "dcbabcd" Constraints: 0 <= s.length <= 5 * 10 4 s consists of lowercase English letters only.
Detailed Explanation
The problem asks us to find the shortest palindrome that can be formed by adding characters to the beginning of a given string 's'. The goal is to return this shortest palindrome.
Solution Approach
The solution leverages the concept of finding the longest palindromic prefix of the input string 's'. It constructs a new string 'temp_s' by concatenating 's', a delimiter '#', and the reverse of 's'. Then, it computes the LPS (Longest Proper Prefix which is also a Suffix) array for 'temp_s' using a modified KMP algorithm. The last element of the LPS array indicates the length of the longest palindromic prefix of 's'. Finally, the solution constructs the shortest palindrome by reversing the suffix of 's' (the part that's not part of the longest palindromic prefix) and prepending it to the original string 's'.
Step-by-Step Algorithm
- Step 1: Reverse the input string 's' and store it in 'rev_s'.
- Step 2: Create a new string 'temp_s' by concatenating 's', a delimiter '#', and 'rev_s'. The '#' character is crucial to avoid incorrect LPS calculations.
- Step 3: Compute the LPS array for 'temp_s'. The LPS array at index i stores the length of the longest proper prefix of temp_s[0...i] which is also a suffix of temp_s[0...i].
- Step 4: The last element of the LPS array represents the length of the longest palindromic prefix of the original string 's'.
- Step 5: Extract the suffix of 's' that is not part of the longest palindromic prefix.
- Step 6: Reverse the extracted suffix.
- Step 7: Prepend the reversed suffix to the original string 's' to create the shortest palindrome.
Key Insights
- Insight 1: The shortest palindrome can be found by identifying the longest palindromic prefix of the given string 's'.
- Insight 2: The KMP algorithm's longest proper prefix which is also a suffix (LPS) array computation can be adapted to find the longest palindromic prefix.
- Insight 3: By concatenating the original string 's', a special character '#', and the reversed string of 's', we can use the LPS array to find the length of the longest palindromic prefix of 's'.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: String, Rolling Hash, String Matching, Hash Function.
Companies
Asked at: Accenture, Google, Pocket Gems, Visa, eBay.