SDE & MLE Prep

680. Valid Palindrome II

Problem

Decide whether s can become a palindrome after deleting at most one character.

Example: "abca" → true (delete c); "abc" → false

Constraints: length ≤ 10⁵.

Walk inward; at the first mismatch you may delete one char: check whether s[l+1..r] or s[l..r-1] is a palindrome.

Complexity: O(n).

class Solution:
    def validPalindrome(self, s: str) -> bool:
        def pal(l, r):
            while l < r:
                if s[l] != s[r]:
                    return False
                l, r = l + 1, r - 1
            return True

        l, r = 0, len(s) - 1
        while l < r:
            if s[l] != s[r]:
                return pal(l + 1, r) or pal(l, r - 1)
            l, r = l + 1, r - 1
        return True