KatInterview

Trim Letters to Reach a Mirror String Within a Budget

Dynamic ProgrammingAuto-graded · 28 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingpalindromestrings

Last 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 is True only when text is already a palindrome.
  • If text is already a palindrome, the answer is True for any budget.
  • If budget >= len(text) - 1, the answer is always True, because you can reduce the string to a single character.
  • The result must be a boolean (True or False).

Constraints

  • 1 <= len(text) <= 2000
  • 0 <= budget <= len(text)
  • text contains only lowercase English letters (a to z).

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.