23(May) K-Palindrome
23. K-Palindrome
The problem can be found at the following link: Question Link
Problem Description
Given a string str of length n, determine if the string is a K-Palindrome. A K-Palindrome string is one that can be transformed into a palindrome by removing at most k characters from it.
Examples:
Example 1:
Input:
str = "abcdecba"
n = 8, k = 1
Output: 1
Explanation: By removing 'd' or 'e' we can make it a palindrome.Example 2:
Input:
str = "abcdefcba"
n = 9, k = 1
Output: 0
Explanation: By removing a single character we cannot make it a palindrome.My Approach
Initialization:
Create two vectors
prevandcurrof sizen+1initialized to 0, which will help store the length of the longest palindromic subsequence (LPS) dynamically.
Dynamic Programming Table Calculation:
Iterate through the string with two nested loops to fill the
currvector based on the previous results stored inprev.If characters
str[i-1]andstr[n-j]are the same, updatecurr[j]toprev[j-1] + 1.Otherwise, set
curr[j]to the maximum ofprev[j]andcurr[j-1].Swap
prevandcurrfor the next iteration.
Determine Minimum Deletions:
The length of the longest palindromic subsequence (LPS) is stored in
prev[n]after the loops.Calculate the minimum deletions needed to transform the string into a palindrome as
minDeletions = n - lps.If
minDeletionsis less than or equal tok, return 1, indicating the string is a K-Palindrome; otherwise, return 0.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n*n), as we iterate through the string with two nested loops up to length
n.Expected Auxiliary Space Complexity: O(n), as we use two vectors of size
n+1for storing intermediate results.
Code
C++
Java
Python
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated