> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Valid Palindrome III Python Solution

> Tested Python solution for LeetCode 1216 with 24 pytest cases. Generate a practice environment with lcpy.

LeetCode 1216, [Hard](/catalog/hard). Topics: [String](/catalog/topics/string), [Dynamic Programming](/catalog/topics/dynamic-programming). [View on LeetCode](https://leetcode.com/problems/valid-palindrome-iii/description/).

Generate this problem as a practice environment: tested reference solution, 24 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1216   # by problem number
lcpy gen -s valid_palindrome_iii   # by problem name
```

## 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.

### Examples

```
Input: s = "abcdeca", k = 2
Output: true
```

**Explanation:** Remove 'b' and 'e' characters.

```
Input: s = "abbababa", k = 1
Output: true
```

### Constraints

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

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/valid_palindrome_iii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/valid_palindrome_iii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n^2)
    # Space: O(n)
    def is_valid_palindrome(self, s: str, k: int) -> bool:
        n = len(s)
        dp = [0] * n
        for i in range(n - 1, -1, -1):
            prev = 0
            dp[i] = 1
            for j in range(i + 1, n):
                temp = dp[j]
                if s[i] == s[j]:
                    dp[j] = prev + 2
                else:
                    dp[j] = max(dp[j], dp[j - 1])
                prev = temp
        return n - dp[n - 1] <= k
```

## Complexity

| Time | Space |
| - | - |
| O(n^2) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.