Problem Description
Given a string s and an integer k, determine 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.
Key Insights
- The problem can be reframed as determining the minimum number of deletions needed to convert the string into a palindrome.
- This minimum deletion count equals (length of s - length of the longest palindromic subsequence (LPS)).
- If (s.length - LPS) is less than or equal to k, the string is k-palindrome.
- Dynamic Programming is used to calculate the LPS in O(n^2) time.
Space and Time Complexity
Time Complexity: O(n^2) where n is the length of the string s. Space Complexity: O(n^2) for the DP table used to compute the longest palindromic subsequence.
Solution
We solve the problem by computing the length of the longest palindromic subsequence (LPS) using dynamic programming. The LPS problem involves finding the longest subsequence that is a palindrome. We set up a 2D DP table dp where dp[i][j] represents the length of the LPS within the substring s[i...j]. If s[i] equals s[j], then these two characters can contribute to the LPS; otherwise, we take the maximum of the two possible substrings (excluding either s[i] or s[j]). After computing dp[0][n-1] (which contains the LPS for the whole string), we check if the difference (s.length - LPS) is within k removals.