Fewest Characters to Prepend So a Query Becomes a Palindrome
Last updated: November 29, 2026
Quick Overview
Given a string s, return the shortest palindrome that can be formed by adding characters only to the front of s, in linear time.
0
0
0 solved
Given a string s, return the shortest palindrome that can be formed by adding characters only to the front of s, in linear time.
A Google technical screen string-algorithms question that starts with an easy quadratic idea and asks for linear time. The interviewer wants you to reduce it to finding the longest palindromic prefix and to compute that with the KMP prefix function on a combined string, explaining why the separator is needed.
What the Interviewer Expects
- Reduces the problem to the longest palindromic prefix of s
- Gives the O(n^2) check of each prefix as a baseline
- Builds s + separator + reverse(s) and computes its prefix function
- Explains why the separator prevents borders longer than s
- Validates against brute force on random inputs
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Solve it with rolling hashes instead and discuss the collision risk.
- Find the shortest palindrome formed by appending characters to the end.
- How would Manacher's algorithm solve the same problem?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input: a string
sof any characters except a reserved separator. Output: the shortest palindrome of the formx + s. aacecaaagivesaaacecaaa;abcdgivesdcbabcd.- Target O(n)....
High-Level Design
If s[:k] is the longest prefix of s that is a palindrome, the answer is reverse(s[k:]) + s: the remaining tail must be mirrored in front, and no shorter addition works because a shorter one woul...