Valid Palindrome II — LeetCode 680 Python Solution
EasyGreedyTwo PointersString
- Problem
- #680
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
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 TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(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
LeetCode 125Valid PalindromeEasyLeetCode 942DI String MatchEasyLeetCode 1147Longest Chunked Palindrome DecompositionHardLeetCode 1754Largest Merge Of Two StringsMediumLeetCode 1850Minimum Adjacent Swaps to Reach the Kth Smallest NumberMediumLeetCode 2193Minimum Number of Moves to Make PalindromeHard
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.