902. Mirror by Prepending
A sign painter has already painted the word s on a banner and is only allowed to add extra letters at the front of it, never in the middle or at the end. The finished banner must read the same forwards and backwards.
Return the shortest banner that can be produced this way. Among all banners of that length there is only one, so the answer is unique. If s is already a palindrome, return it unchanged.
Aim for time O(n) where n is the length of s; testing every prefix for being a palindrome one by one takes O(n^2).
Example 1
- Input:
- s = "fishwife"
- Output:
- "efiwhsifishwife"
- Explanation:
The longest palindromic prefix is just 'f', so the other seven letters are mirrored in front: 'efiwhsi' + 'fishwife' gives 'efiwhsifishwife'.
Example 2
- Input:
- s = "rotorx"
- Output:
- "xrotorx"
- Explanation:
The prefix 'rotor' is already a palindrome; only 'x' has to be mirrored in front, giving 'xrotorx'.
Example 3
- Input:
- s = "wowow"
- Output:
- "wowow"
- Explanation:
The whole string is a palindrome, so nothing is added.
Constraints
1 ≤ s.length ≤ 105
s contains only lowercase English letters.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)