KatInterview

Minimum Single-Character Edits to Make a Palindrome

StringsAuto-graded · 18 test cases
EasyAuto-gradedStringsstringsdynamic programmingedit operations

Last updated

Tests whether a candidate can count the minimum number of single-character insertions or deletions needed to transform a string into any palindrome.

Minimum Single-Character Edits to Make a Palindrome

Given a string s, you may perform two kinds of edit operations, each costing 1:

  • Insert any single character at any position in the string.
  • Delete any single character from the string.

Return the minimum total number of edits required to turn s into a palindrome.

A palindrome reads the same forwards and backwards (e.g. "racecar", "abba", "a", "").

Note: Substitution is not allowed — only insertions and deletions count.

How to think about it

Consider which characters already "match" across the two ends of the string. The longest palindromic subsequence (LPS) of s is the largest set of characters you can keep without any edits; every other character must be removed or paired with an inserted mirror. The answer is therefore len(s) − LPS(s).

Constraints

  • 0 ≤ len(s) ≤ 1000
  • s contains only lowercase English letters (a–z).
  • The empty string "" is already a palindrome; return 0.
  • A single character is already a palindrome; return 0.

Examples

Example 1

Input: min_edits_to_palindrome('race')

Output: 3

Example 2

Input: min_edits_to_palindrome('abcba')

Output: 0

Example 3

Input: min_edits_to_palindrome('')

Output: 0

Hints

Hint 1

Think about which characters you can keep: the longest subsequence of s that is already a palindrome needs no edits. Everything else requires one edit per character.

Hint 2

The Longest Palindromic Subsequence (LPS) of s equals the Longest Common Subsequence (LCS) of s and reverse(s). Build a 2-D DP table of size (n+1) × (n+1).

Hint 3

The answer is len(s) − LPS(s), because each character outside the LPS needs exactly one insertion or deletion to fix the palindrome property.