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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Hard

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
KMP Prefix Function
Palindromes
String Matching
Linear Time
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements
  • Input: a string s of any characters except a reserved separator. Output: the shortest palindrome of the form x + s.
  • aacecaaa gives aaacecaaa; abcd gives dcbabcd.
  • 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...


Submit Your Answer
Markdown supported