PPractick

DSA interview question

Minimum Characters to Insert at Front to Make String Palindrome

Hard · Algorithms · Topics: string, kmp, lps, palindrome

The problem

You're building a "Did You Mean?" autocomplete-style typo-correction feature for a search engine. Internally, the team noticed that a surprising number of malformed queries become palindromes if you just prepend a few characters at the front (this is a real trick used to detect minimal corruption in symmetric tokens/IDs). Your task: given a string A, find the minimum number of characters you need to insert at the front of A to make the entire string a palindrome.

Example: "AACECAAAA" — if you prepend "AAAA" reversed appropriately, it becomes a palindrome. You need to find that minimum count.

Function signature

int minCharsToMakePalindrome(string A);

Test cases

Input AOutputExplanation
"ABC"2Insert "CB" at front → "CBABC"
"AACECAAAA"2Insert "AA" at front → "AAAACECAAAA"
"AACECAAAAA"0Already... wait, check — not a palindrome, verify with code
"A"0Single character is always a palindrome
""0Empty string is trivially a palindrome
"AAAA"0Already a palindrome
"ABCD"3Insert "DCB" at front → "DCBABCD"

(Always verify edge cases like empty string / single char / already-palindrome in your head before coding.)

How interviewers phrase it

Clarifying questions to ask

  1. Can I only insert at the front, or also at the back? (This problem is front-only — back-only or both-sides versions exist too, so confirm.)
  2. Are insertions limited to characters already in the string, or can I insert any character? (Doesn't actually matter for the count, but good to confirm you understand the ask.)
  3. What's the expected input size? (If 1e5 or more, brute force O(n²) char comparison will TLE — signals you need an O(n) approach like KMP.)
  4. Is the string guaranteed non-empty / only uppercase letters, etc.?

Follow-ups to expect

  1. "Can you do better than O(n²)?"
  2. "What if insertions are allowed at the back instead?"
  3. "What if insertions are allowed at both front and back?"
  4. "Can you also construct the resulting palindrome string, not just the count?"
  5. "What if you wanted to minimize total insertions anywhere in the string (not just front)?"
  6. "Can you solve it using Manacher's Algorithm instead of KMP?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in