You get a string s. You may add letters to the front of it, and nowhere else, until it reads the same forwards and backwards.
Return the shortest palindrome you can make this way.
Example 1
Input: s = "abac" Output: "cabac" Why: "aba" is already a palindrome; add the reversed "c" in front
2 more examples and the constraints
Example 2
Input: s = "xyz" Output: "zyxyz" Why: only "x" is a palindrome prefix, so "zy" goes in front
Example 3
Input: s = "" Output: "" Why: the empty string is already a palindrome
Constraints
- 0 ≤ length of s ≤ 50,000
- s holds only lowercase English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every prefixO(n²)
- KMP failure functionO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50,000 letters | Verdict |
|---|---|---|---|
| Try every prefix | O(n²) | Too slow on bad inputs | |
| KMP failure function | O(n) | Best; linear every time |
n = length of s.
Edge cases to test
- Empty string. "" is already a palindrome; return "".
- Already a palindrome. "racecar" needs nothing added.
- Only the first letter fits. "xyz" adds n − 1 letters: "zyxyz".
- Repeated letters. "aaab" keeps "aaa" and adds one b: "baaab".
Common mistakes
- Leaving out the
#, so a match runs across the middle and keep becomes longer than s. - Adding letters to the end or the middle; only the front is allowed.
- Taking the first palindrome prefix found from the short end instead of the longest one.
How to talk through it
- 1Clarify. Only the front can change? Can s be empty? What letters can appear?
- 2Reduce it. The answer is the reversed tail plus s, so the job is the longest palindrome prefix.
- 3Give the brute force. Try prefixes longest first, O(n²), and show the input that makes it slow.
- 4Use KMP. That prefix is the longest prefix of s that is a suffix of reversed s: the failure table of s + # + reversed s.
- 5Test out loud. Run "", "racecar", "xyz" and "aaab" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?