Tensorum
LeetCode 680 · Two Pointers

Valid Palindrome II

LeetCode 680 · Easy · solution, intuition & step-by-step walkthrough

On the first mismatch, try both deletions once.

EasyTwo PointersStringGreedy
59 msruntime · beats 51%
16.9 MBmemory · beats 100%
1approach
2accepted runs · last 5 Nov 2024

This is how I solved Valid Palindrome II (LeetCode 680), an easy problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Walk inward from both ends. At the first mismatch you get one deletion: try skipping the left character or the right character, and check whether what remains between the pointers is a palindrome.

Approach

  1. 1

    Two pointers from the ends.

  2. 2

    Matching characters: move inward.

  3. 3

    Mismatch: return palindrome(i+1, j) or palindrome(i, j−1).

How I solved it

Two pointers + one skipPythonO(n) time · O(1) space
class Solution:
    def check_palindrome(self,i,j,s) ->bool:
        while i<j:
            if s[i]!=s[j]:
                return False
            i+=1
            j-=1        
        return True

    def validPalindrome(self, s: str) -> bool:
        i,j=0,len(s)-1
        while(i<j):
            #Found a mismatched pair, try both deletions
            if s[i]!=s[j]:
                return self.check_palindrome(i+1,j,s) or self.check_palindrome(i,j-1,s)
            i=i+1
            j=j-1
        return True
Loading the step-through…

Valid Palindrome II — FAQ

What is the intuition behind Valid Palindrome II?

Walk inward from both ends. At the first mismatch you get one deletion: try skipping the left character or the right character, and check whether what remains between the pointers is a palindrome.

How do you solve Valid Palindrome II (LeetCode 680)?

1. Two pointers from the ends. 2. Matching characters: move inward. 3. Mismatch: return palindrome(i+1, j) or palindrome(i, j−1).

What is the time and space complexity of Valid Palindrome II?

Time: O(n). Space: O(1). (Accepted approach: Two pointers + one skip.)

What are common mistakes in Valid Palindrome II?

Only one deletion is allowed — don't recurse with another deletion budget.