PPractick

DSA interview question

Minimum Insertions to Make a String Palindrome

Hard · Algorithms · Topics: dynamic programming, string, lps

The problem

You're building a "symmetric ID repair" tool for a legacy inventory system, where product codes are supposed to be palindromic (a validation quirk baked in decades ago), but due to a data-entry bug, some codes came out slightly malformed. Unlike the earlier "insert only at front" problem, this time insertions are allowed anywhere in the string — front, back, or middle. Given a string s, find the minimum number of characters you need to insert (anywhere) to make it a palindrome.

Function signature

int minInsertionsToPalindrome(string s);

Test cases

Input sOutputExplanation
"zzazz"0already a palindrome
"mbadm"2insert "b" and "d" appropriately → "mbdadbm" (one valid result), length 7
"leetcode"5needs 5 insertions to become a palindrome
"g"0single character is always a palindrome
""0empty string is trivially a palindrome
"ab"1insert "a" or "b" → "aba" or "bab"
"aa"0already a palindrome

(This is LeetCode 1312 — distinct from the earlier "front-only" LPS/KMP problem. Confirm which variant is being asked.)

How interviewers phrase it

Clarifying questions to ask

  1. Can insertions happen anywhere in the string (front, middle, back), or only at one end? (Critical — if only front, it's the KMP/LPS-prefix problem instead; if anywhere, it's this DP problem.)
  2. Is deletion allowed too, or strictly insertions only?
  3. Are we minimizing insertion count, or do we also need the final palindrome string itself?
  4. Case-sensitive matching?
  5. What's the expected string length? (Signals whether O(n²) DP is fine, or if they want the O(n log n) LCS-via-suffix-array style optimization — usually O(n²) is fully acceptable here.)

Follow-ups to expect

  1. "How does this relate to Longest Palindromic Subsequence (LPS)?"
  2. "How does this relate to LCS?"
  3. "Can you reconstruct the actual palindrome, not just the count?"
  4. "Can you optimize space?"
  5. "What if insertions had different costs depending on the character?"
  6. "Compare/contrast with the 'insert only at front' version you solved earlier."

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