{x}
blog image

Valid Palindrome III

Solution Explanation: 1216. Valid Palindrome III

This problem asks whether a given string s can be transformed into a palindrome by removing at most k characters. The optimal approach uses dynamic programming to find the length of the longest palindromic subsequence within s.

Core Idea:

The solution leverages the concept of longest palindromic subsequence (LPS). If the length of the LPS is len(LPS), then we only need to remove len(s) - len(LPS) characters to make the string a palindrome. If this removal count is less than or equal to k, the string is a k-palindrome.

Dynamic Programming Approach:

A 2D array f[i][j] stores the length of the LPS within the substring s[i...j].

  • Base Case: f[i][i] = 1 (each single character is a palindrome).

  • Recursive Relation:

    • If s[i] == s[j]: f[i][j] = f[i+1][j-1] + 2 (extend the LPS from s[i+1...j-1]).
    • If s[i] != s[j]: f[i][j] = max(f[i+1][j], f[i][j-1]) (either remove s[i] or s[j]).

The algorithm iterates through the substrings in a bottom-up manner, filling the f array. If at any point f[i][j] + k >= len(s), it implies that we can make the string a palindrome by removing at most k characters, and we return true.

Time and Space Complexity:

  • Time Complexity: O(n^2) - The nested loops iterate through all possible substrings of length O(n^2).
  • Space Complexity: O(n^2) - The f array requires O(n^2) space.

Code Implementation (Python):

class Solution:
    def isValidPalindrome(self, s: str, k: int) -> bool:
        n = len(s)
        f = [[0] * n for _ in range(n)]
        for i in range(n):
            f[i][i] = 1
        for i in range(n - 2, -1, -1):
            for j in range(i + 1, n):
                if s[i] == s[j]:
                    f[i][j] = f[i + 1][j - 1] + 2
                else:
                    f[i][j] = max(f[i + 1][j], f[i][j - 1])
                if f[i][j] + k >= n:  #Check if k-palindrome condition is met
                    return True
        return False
 

The code implementations in other languages (Java, C++, Go, TypeScript, Rust) follow the same dynamic programming logic, differing only in syntax and data structure handling. They all achieve the same time and space complexity.