Valid Palindrome III

Updated on 10 July, 2025
Valid Palindrome III header image

Problem Statement

In the task, we are given a string s and an integer k. The objective is to determine if the string s can be considered a k-palindrome. A string qualifies as a k-palindrome if it can be transformed into a palindrome by removing at most k characters. The challenge lies in deciding whether such a transformation is possible and if so, confirming the minimum number of deletions required does not exceed k.

Examples

Example 1

Input:

s = "abcdeca", k = 2

Output:

true

Explanation:

Remove 'b' and 'e' characters.

Example 2

Input:

s = "abbababa", k = 1

Output:

true

Constraints

  • 1 <= s.length <= 1000
  • s consists of only lowercase English letters.
  • 1 <= k <= s.length

Approach and Intuition

The solution to the problem involves an understanding of palindromes and how characters can be manipulated to form one. The core idea revolves around comparing the string with its reverse and identifying positions where the characters do not match, as these mismatches dictate the deletions required.

  1. First, compute the reverse of the string s to facilitate character-by-character comparison from both ends toward the center.
  2. Utilize dynamic programming to find the Longest Common Subsequence (LCS) between the string s and its reverse. The rationale here is that a palindrome reads the same forwards and backwards. Thus, the LCS will represent the largest palindrome that can be formed by deleting characters from s.
  3. Once the LCS is calculated, the minimum deletions needed to convert s into a palindrome equals the total length of s minus the length of the LCS.
  4. Lastly, if the number of deletions required to turn s into a palindrome is less than or equal to k, return true; otherwise, return false.

By working through this method, we ensure that we are efficiently determining the possibility of transforming s into a palindrome with a constraint on deletions, respecting the problem's k limit.

Solutions

  • C++
cpp
class Solution {
public:
    bool canFormPalindrome(string str, int maxDeletions) {
        vector<int> dp(str.size(), 0);
        int curPrev, lastPrev;
    
        for (int start = str.size() - 2; start >= 0; start--) {
            lastPrev = 0;
            for (int end = start + 1; end < str.size(); end++) {
                curPrev = dp[end];
    
                if (str[start] == str[end])
                    dp[end] = lastPrev;
                else
                    dp[end] = 1 + min(dp[end], dp[end - 1]);
    
                lastPrev = curPrev;
            }
        }
    
        return dp[str.size() - 1] <= maxDeletions;
    }
};

This solution summary addresses the problem of determining if a given string can be transformed into a palindrome by deleting at most a specified number of characters, using C++.

  • The function canFormPalindrome takes two parameters: the string str and an integer maxDeletions representing the maximum characters that can be deleted.
  • It utilizes a dynamic programming approach by creating a vector dp of integers, initialized to zeros and sized according to the length of str.
  • The double loop iterates through the string in reverse for the outer loop (start) and from the current start point to the end of the string in the inner loop (end).
  • The variable lastPrev tracks the results from the previous iteration, and curPrev temporarily stores the current value of dp[end].
  • Inside the inner loop:
    • If the characters at positions start and end of the string match, the value at dp[end] is updated to the value of lastPrev (indicating no new deletions are needed for these positions to match).
    • If the characters do not match, the function computes the minimum of dp[end] and dp[end - 1] plus one. This represents the minimum deletions needed to make the substring palindrome up to that point.
  • After the loops, the function checks if the value at the last index of dp is less than or equal to maxDeletions to decide whether the string can be transformed into a palindrome under the given constraints.
  • The function returns a boolean indicating whether the transformation is possible.

This approach leverages dynamic programming to efficiently determine the minimum deletions required for palindrome transformation, ensuring optimal performance across varying string lengths and conditions.

  • Java
java
class Solution {
public boolean canFormPalindrome(String str, int maxDeletions) {
        int dp[] = new int[str.length()];
        int curr, previous;
        for (int start = str.length() - 2; start >= 0; start--) {
            previous = 0;
            for (int end = start + 1; end < str.length(); end++) {
                curr = dp[end];
                if (str.charAt(start) == str.charAt(end))
                    dp[end] = previous;
                else
                    dp[end] = 1 + Math.min(dp[end], dp[end - 1]);
                previous = curr;
            }
        }
        return dp[str.length() - 1] <= maxDeletions;
    }
};

The provided solution determines if a given string can be converted into a palindrome by deleting at most a specified number of characters. The approach utilizes dynamic programming to achieve this.

Here’s a brief rundown of the implementation:

  • A dp array is initialized of the same length as the input string to store the minimum deletions needed for each substring.
  • The outer loop iterates the string from the second to last character to the beginning.
  • For each character, a nested loop from the current character to the end of the string checks:
    • If the characters at both ends of the current substring are the same, it inherits the value from the previous iteration (previous value), which suggests no deletion is needed for these characters to match.
    • If they are different, it calculates the minimum deletions needed by either deleting the start or the end character of the substring.
  • Update the current minimum deletions in the dp array accordingly.
  • After filling up the dp array, check if the last value (which represents the entire string) is less than or equal to maxDeletions allowed. If it is, the string can be converted into a palindrome within the given deletion limit.

This algorithm intelligently leverages dynamic programming to compute the minimum deletions required for each substring, optimizing the palindrome check efficiently. The final value in the dp array tells if transforming the whole string into a palindrome is feasible under the given constraints.

Comments

No comments yet.