KatInterview

Minimum Edit Distance to Make String a Palindrome

StringsAuto-graded · 17 test cases
MediumAuto-gradedStringsstringsdynamic programmingpalindromes

Last updated

Tests whether a candidate can compute the minimum number of single-character insertions needed to transform an arbitrary string into a palindrome using interval DP.

Minimum Insertions to Form a Palindrome

Given a string s, return the minimum number of character insertions needed to make s a palindrome.

In a single insertion you may place any character at any position in the string.

How it works

  • You may only insert characters (no deletions, no substitutions).
  • You want the resulting string to read the same forwards and backwards.
  • Return the smallest number of insertions that achieves this.

Key observations

  • An empty string and a single character are already palindromes (answer is 0).
  • If the first and last characters of s match, no extra insertion is needed at the outermost level — you only need to fix the interior.
  • If they differ, one insertion is required to balance the mismatch, then you recurse on the best sub-problem.

Constraints

  • 0 ≤ len(s) ≤ 2000
  • s contains only lowercase English letters ('a'–'z').
  • An empty string is already a palindrome; return 0.

Examples

Example 1

Input: min_insertions_palindrome('abca')

Output: 1

Example 2

Input: min_insertions_palindrome('racecar')

Output: 0

Example 3

Input: min_insertions_palindrome('')

Output: 0

Hints

Hint 1

Think about the relationship between this problem and the Longest Palindromic Subsequence — the answer is len(s) minus the length of the longest palindromic subsequence.

Hint 2

Try an interval DP on substrings: let dp[i][j] = minimum insertions to make s[i..j] a palindrome. Base cases: dp[i][i] = 0 (single char) and dp[i][i-1] = 0 (empty).

Hint 3

Recurrence: if s[i] == s[j], then dp[i][j] = dp[i+1][j-1]; otherwise dp[i][j] = 1 + min(dp[i+1][j], dp[i][j-1]).