Trim Letters to Reach a Mirror String Within a Budget
Dynamic ProgrammingAuto-graded · 28 test casesLast updated
Decide whether a string can become a palindrome after removing no more than k characters, testing interval dynamic programming and palindromic subsequence reasoning.
Trim Letters to Reach a Mirror String Within a Budget
You are given a string text made of lowercase English letters and a non-negative integer budget.
You may delete characters from text, at any positions, and the remaining characters keep their original relative order. You may delete at most budget characters (deleting none is allowed).
Return True if the remaining string can be a palindrome, and False otherwise. A palindrome reads the same forward and backward. The empty string and any single character count as palindromes.
Rules and edge cases
- If
budget == 0, the answer isTrueonly whentextis already a palindrome. - If
textis already a palindrome, the answer isTruefor anybudget. - If
budget >= len(text) - 1, the answer is alwaysTrue, because you can reduce the string to a single character. - The result must be a boolean (
TrueorFalse).
Constraints
1 <= len(text) <= 20000 <= budget <= len(text)textcontains only lowercase English letters (atoz).
Examples
Example 1
Input: can_mirror_with_removals('abca', 1)
Output: True
Example 2
Input: can_mirror_with_removals('abcdeca', 2)
Output: True
Example 3
Input: can_mirror_with_removals('abcdef', 2)
Output: False
Hints
Hint 1
Any string obtained by deleting characters is a subsequence of the original. Ask what the longest palindromic subsequence tells you about the minimum number of deletions.
Hint 2
Define f(i, j) as the fewest deletions that make text[i..j] a palindrome. If the end characters match, f(i, j) = f(i+1, j-1); otherwise one of the two ends must go, so f(i, j) = 1 + min(f(i+1, j), f(i, j-1)).
Hint 3
A full 2D table is fine for n = 2000, but each row only needs the row below it plus one saved diagonal value, so you can reduce the memory to a single array.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Whatever remains after deleting characters is a subsequence of the original string. So the question is whether the minimum number of deletions needed to make the string a palindrome is at most budget.
Let f(i, j) be the minimum deletions needed to turn text[i..j] into a palindrome.
- If
i >= j(empty or single character),f(i, j) = 0. - If
text[i] == text[j], keep both ends:f(i, j) = f(i+1, j-1). - Otherwise the two ends cannot both be the outermost pair, so at least one is deleted:
f(i, j) = 1 + min(f(i+1, j), f(i, j-1)).
The answer is f(0, n-1) <= budget.
Why it is correct
- Matching ends: keeping both is never worse than deleting one. If an optimal solution drops
text[i], the outer pair can be swapped to usetext[i]andtext[j]without using extra deletions (the usual exchange argument for the longest palindromic subsequence). - Mismatched ends: at least one end must be removed, and both choices are explored, so the minimum is found. A greedy choice fails because the two options lead to different subproblems.
Space optimization
Row i of the table depends only on row i+1 and on earlier cells of row i. A single array dp is enough, with i going from n-2 down to 0 and j going left to right:
dp[j]before being overwritten isf(i+1, j).dp[j-1](already updated) isf(i, j-1).previousholds the olddp[j-1], i.e.f(i+1, j-1). It is reset to0at the start of every row, which covers the empty-substring case whenj = i+1.
The cell dp[i] is never written during rows >= i, so it stays 0, which encodes f(i, i) = 0.
Shortcuts: when budget >= n - 1 the answer is True; when budget == 0 it is a direct palindrome check.
Complexity
- Time: O(n²), about 2 million steps for n = 2000.
- Space: O(n).
Reference solution
def can_mirror_with_removals(text: str, budget: int) -> bool:
n = len(text)
if n <= 1 or budget >= n - 1:
return True
if budget == 0:
return text == text[::-1]
# dp[j] = minimum deletions to make text[i..j] a palindrome
# for the current start index i (before overwrite it holds row i+1).
dp = [0] * n
for i in range(n - 2, -1, -1):
previous = 0 # value for the substring text[i+1..j-1]
for j in range(i + 1, n):
old = dp[j]
if text[i] == text[j]:
dp[j] = previous
else:
dp[j] = min(dp[j], dp[j - 1]) + 1
previous = old
return dp[n - 1] <= budget