Valid Palindrome II — LeetCode 680 Python Solution

EasyGreedyTwo PointersString
Problem
#680
Reading time
3 min

The problem

Given a string s, return true if the s can be palindrome after deleting at most one character from it.

Example

Input
s = "aba"
Output
true

Python solution

Python
class Solution:
    def validPalindrome(self, s: str) -> bool:
        def check(i, j):
            while i < j:
                if s[i] != s[j]:
                    return False
                i, j = i + 1, j - 1
            return True

        i, j = 0, len(s) - 1
        while i < j:
            if s[i] != s[j]:
                return check(i, j - 1) or check(i + 1, j)
            i, j = i + 1, j - 1
        return True

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 680. Valid Palindrome II is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 680. Valid Palindrome II?
LeetCode 680. Valid Palindrome II is rated Easy on LeetCode.
What is the time complexity of LeetCode 680. Valid Palindrome II?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 680. Valid Palindrome II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 680. Valid Palindrome II cover?
LeetCode 680. Valid Palindrome II is tagged Greedy, Two Pointers and String on LeetCode.

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