Minimum Edits to Make a String k-Palindromic
StringsAuto-graded · 19 test casesLast 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
- Choose any
kindices to delete froms— this gives a subsequence of lengthn - k. - Apply the minimum number of character substitutions to that subsequence to make it a palindrome.
- Return the minimum such substitution count over all possible choices of which k characters to delete.
Constraints
1 <= len(s) <= 10000 <= k <= len(s)sconsists 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Insight
We want to delete exactly k characters from s and then apply the fewest character substitutions to make the remaining subsequence (of length L = n - k) a palindrome. The two degrees of freedom are:
- Which k characters to delete (choosing the subsequence).
- What substitutions to apply to the chosen subsequence.
We handle both simultaneously with a recursive DP.
DP Definition
dp(i, j, remaining_len)
= minimum substitutions needed to select a palindromic subsequence of length exactly remaining_len from s[i..j].
Recurrence
At each call we have three choices:
- Use both ends as an outer pair: pay
0ifs[i] == s[j], else1, then recurse ondp(i+1, j-1, remaining_len - 2). - Skip
s[i](delete it): recurse ondp(i+1, j, remaining_len). - Skip
s[j](delete it): recurse ondp(i, j-1, remaining_len).
Take the minimum over all three options.
Base Cases
remaining_len <= 1: answer is0(empty or single char is always a palindrome).remaining_len == 2: scans[i..j]for any two equal characters; cost0if found, else1.span < remaining_len: impossible, return infinity.
Correctness
Every valid choice of k deletions and subsequent substitutions corresponds to some path through this DP. The DP explores all ways to build a length-L palindromic subsequence and finds the one requiring fewest substitutions.
Complexity
- States: O(n² × L) = O(n³) in the worst case.
- Per state: O(1) work (the
remaining_len == 2scan is O(n) but occurs only at the bottom level and across O(n²) states = O(n³) total in the worst case, dominated by the state space anyway). - Space: O(n³) for the memoisation table.
For n ≤ 1000 the state space can be up to 10⁹ in theory, but in practice the recursion is pruned heavily because remaining_len decreases by 2 with each "use both ends" step, and real inputs have L well under n. The problem constraints keep this tractable.
Reference Solution
from typing import List
import functools
def min_edits_k_palindromic(s: str, k: int) -> int:
n = len(s)
target_len = n - k
if target_len <= 1:
return 0
@functools.lru_cache(maxsize=None)
def dp(i: int, j: int, remaining_len: int) -> int:
span = j - i + 1
if remaining_len <= 0:
return 0
if remaining_len == 1:
return 0
if span < remaining_len:
return 10**9
if remaining_len == 2:
chars = {}
for idx in range(i, j + 1):
if s[idx] in chars:
return 0
chars[s[idx]] = idx
return 1
cost_A = (0 if s[i] == s[j] else 1) + dp(i + 1, j - 1, remaining_len - 2)
cost_B = dp(i + 1, j, remaining_len)
cost_C = dp(i, j - 1, remaining_len)
return min(cost_A, cost_B, cost_C)
result = dp(0, n - 1, target_len)
dp.cache_clear()
return result