Valid Palindrome III — LeetCode 1216 Python Solution

HardLeetCode PremiumStringDynamic Programming
Problem
#1216
Reading time
3 min

The 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

Input
s = "abcdeca", k = 2
Output
true
Explanation
Remove 'b' and 'e' characters.

Python solution

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:
                    return True
        return False

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n^2) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1216. Valid Palindrome III is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1216. Valid Palindrome III?
LeetCode 1216. Valid Palindrome III is rated Hard on LeetCode.
What is the time complexity of LeetCode 1216. Valid Palindrome III?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 1216. Valid Palindrome III?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 1216. Valid Palindrome III cover?
LeetCode 1216. Valid Palindrome III is tagged String and Dynamic Programming on LeetCode.
Is LeetCode 1216. Valid Palindrome III a premium problem?
Yes. LeetCode 1216. Valid Palindrome III is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview