KatInterview

Minimum Edits to Make a String k-Palindromic

StringsAuto-graded · 19 test cases
MediumAuto-gradedStringsstringsdynamic-programmingedit-operations

Last updated

Tests the ability to combine classic edit-distance dynamic programming with palindrome structure to find the minimum single-character substitutions needed to make a string palindromic after removing exactly k characters.

Minimum Edits to Make a String k-Palindromic

A string is called k-palindromic if you can delete exactly k characters from it (at any positions) to produce a palindrome. The remaining characters must form a palindrome — they are not rearranged, only the deleted characters are removed.

After choosing which k characters to delete, you are allowed to perform character substitutions on the remaining string to make it a palindrome. Each substitution replaces one character with any other character and costs 1 edit.

Given a string s and a non-negative integer k, return the minimum number of substitution edits needed so that some choice of k deletions from s leaves a palindrome.

If len(s) - k <= 1, a single character (or empty string) is always a palindrome, so the answer is 0.

You may not delete more characters than the string contains; it is guaranteed that k <= len(s).

How edits and deletions interact

  1. Choose any k indices to delete from s — this gives a subsequence of length n - k.
  2. Apply the minimum number of character substitutions to that subsequence to make it a palindrome.
  3. Return the minimum such substitution count over all possible choices of which k characters to delete.

Constraints

  • 1 <= len(s) <= 1000
  • 0 <= k <= len(s)
  • s consists of lowercase English letters only.
  • The answer is always a non-negative integer.

Examples

Example 1

Input: min_edits_k_palindromic('abcba', 0)

Output: 0

Example 2

Input: min_edits_k_palindromic('abcde', 1)

Output: 2

Example 3

Input: min_edits_k_palindromic('abcda', 2)

Output: 0

Hints

Hint 1

Think about what it means to make a subsequence of length (n-k) a palindrome with the fewest substitutions. The minimum substitutions to make a fixed string a palindrome is the number of mismatched pairs when reading from both ends simultaneously.

Hint 2

Consider a 2D DP where dp[i][j] = minimum substitutions to make s[i..j] a palindrome by deleting the optimal characters within that window — this is equivalent to finding the minimum-cost palindrome subsequence of length (n-k).

Hint 3

The recurrence mirrors longest palindromic subsequence DP: if s[i]==s[j], no substitution cost is added for that pair; if s[i]!=s[j], cost 1 is added. You either match the outer characters (cost 0 or 1) and recurse inward, or you skip one end character (a deletion). Track both the number of deletions used and substitution cost, or reformulate so the DP directly gives minimum substitutions for all possible subsequence lengths.