sagelearnai

Valid Palindrome II

Difficulty: Easy · Pattern: Two Pointers · LeetCode #680

Return true if the string s can become a palindrome after deleting at most one character.

Examples

text
"aba"   →  true
"abca"  →  true    (delete 'b' or 'c')
"abc"   →  false

Hints

  1. Compare from both ends while characters match.
  2. At the first mismatch, you get one deletion: skip the left character or skip the right one.
  3. Each option is a plain palindrome check on a substring.

Approach

Move two pointers inward. At the first mismatch s[l] != s[r], the only possible fixes are deleting s[l] or deleting s[r], so check whether s[l+1..r] or s[l..r−1] is a palindrome. If no mismatch occurs, it's already a palindrome. Each check is linear, so the total is O(n).

Complexity

Time: O(n). Space: O(1).

Python solution
def validPalindrome(s):
    def is_pal(i, j):
        while i < j:
            if s[i] != s[j]:
                return False
            i += 1; j -= 1
        return True
    l, r = 0, len(s) - 1
    while l < r:
        if s[l] != s[r]:
            return is_pal(l + 1, r) or is_pal(l, r - 1)
        l += 1; r -= 1
    return True
JavaScript solution
function validPalindrome(s) {
  const isPal = (i, j) => { while (i < j) { if (s[i] !== s[j]) return false; i++; j--; } return true; };
  let l = 0, r = s.length - 1;
  while (l < r) {
    if (s[l] !== s[r]) return isPal(l + 1, r) || isPal(l, r - 1);
    l++; r--;
  }
  return true;
}