Valid Palindrome III - Problem

Given a string s and an integer k, return true if s is a k-palindrome.

A string is k-palindrome if it can be transformed into a palindrome by removing at most k characters from it.

Example:

For string "abcdeca" and k = 2, we can remove characters at positions 1 and 4 ('b' and 'e') to get "acdca", which can be rearranged to form palindrome "aceca". However, this problem asks if we can form a palindrome by removing characters while maintaining their relative order.

Input & Output

Example 1 — Basic k-palindrome
$ Input: s = "abcdeca", k = 2
Output: true
💡 Note: We can remove 'b' and 'd' to get "aceca" which is a palindrome. The minimum deletions needed is 2, which equals k=2, so return true.
Example 2 — Already palindrome
$ Input: s = "abcba", k = 1
Output: true
💡 Note: String is already a palindrome, needs 0 deletions which is ≤ k=1.
Example 3 — Not enough deletions
$ Input: s = "abc", k = 1
Output: false
💡 Note: To make "abc" a palindrome, we need to delete at least 2 characters (e.g., delete 'b' and 'c' to get "a"). Since 2 > k=1, return false.

Constraints

  • 1 ≤ s.length ≤ 1000
  • 0 ≤ k ≤ s.length
  • s consists only of lowercase English letters

Visualization

Tap to expand
Valid Palindrome III INPUT String s: a b c d e c a 0 1 2 3 4 5 6 k = 2 (max removals) Goal: Make palindrome by removing at most 2 chars Remove 'b' and 'd': a c e c a "aceca" is palindrome! ALGORITHM STEPS 1 Find LPS Length Use DP to find Longest Palindromic Subsequence 2 Build DP Table dp[i][j] = LPS length for substring s[i..j] DP Table (partial) i\j 0 1 ... 6 0 1 1 ... 5 1 - 1 ... 4 LPS("abcdeca") = 5 3 Calculate Removals removals = n - LPS = 7 - 5 = 2 4 Check Condition Return removals <= k 2 <= 2? Yes! FINAL RESULT true k-palindrome: OK Verification: String length: n = 7 LPS length: 5 Min removals: 7 - 5 = 2 2 <= k(2): true Palindrome formed: a c e c a Reads same forwards/backwards Key Insight: A string is k-palindrome if (string_length - LPS_length) <= k. The Longest Palindromic Subsequence (LPS) tells us the maximum characters we can keep while forming a palindrome. The remaining characters must be removed. Time: O(n^2), Space: O(n^2) for the DP table. TutorialsPoint - Valid Palindrome III | Optimal Solution (Dynamic Programming)
Asked in
Google 35 Amazon 28 Microsoft 22
28.0K Views
Medium 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