Valid Palindrome III - Problem
Valid Palindrome III is a challenging string manipulation problem that tests your dynamic programming skills.

Given a string s and an integer k, determine if s can become a palindrome by removing at most k characters. A palindrome reads the same forwards and backwards (like "racecar" or "madam").

For example, if s = "abcdeca" and k = 2, we can remove 'b' and 'd' to get "aceca", which is a palindrome. Therefore, the answer is true.

Key insight: This problem is equivalent to finding the longest palindromic subsequence in the string. If the length of the longest palindromic subsequence is at least n - k (where n is the string length), then we can remove at most k characters to form a palindrome.

Input & Output

example_1.py — Basic Case
$ Input: s = "abcdeca", k = 2
› Output: true
šŸ’” Note: We can remove 'b' and 'd' to get "aceca", which is a palindrome. Only 2 characters removed, which is ≤ k.
example_2.py — Impossible Case
$ Input: s = "abbababa", k = 1
› Output: false
šŸ’” Note: The longest palindromic subsequence is "ababa" (length 5). We need to remove 8-5=3 characters, but k=1, so it's impossible.
example_3.py — Edge Case
$ Input: s = "a", k = 0
› Output: true
šŸ’” Note: A single character is already a palindrome, no removals needed.

Visualization

Tap to expand
K-Palindrome Problem VisualizationOriginal String: "abcdeca"abcdecaGreen: Keep (in LPS), Red: RemoveLongest Palindromic Subsequence: "aceca"acecaCalculation:• String length: 7• LPS length: 5• Removals needed: 7 - 5 = 2• Given k: 2• Check: 2 ≤ 2 āœ“ā€¢ Result: TRUE
Understanding the Visualization
1
Identify Core Story
Find the longest palindromic subsequence - this is your core narrative
2
Count Damaged Pages
Characters not in LPS are like damaged pages that must be removed
3
Check Budget
If damaged pages ≤ k, you can afford the restoration
4
Make Decision
Return true if restoration is within budget
Key Takeaway
šŸŽÆ Key Insight: Transform the problem into finding the Longest Palindromic Subsequence. The number of characters to remove equals string length minus LPS length. This reduces a complex problem into a well-known DP pattern.

Time & Space Complexity

Time Complexity
ā±ļø
O(n²)

We fill an nƗn DP table, each cell taking O(1) time

n
2n
⚠ Quadratic Growth
Space Complexity
O(n²)

DP table of size nƗn, can be optimized to O(n) space

n
2n
⚠ Quadratic Space

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of only lowercase English letters
  • 1 ≤ k ≤ s.length
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
28.4K Views
Medium-High Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
šŸ’” Explanation
AI Ready
šŸ’” Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen