EasyNo. 0680
Valid Palindrome II — LeetCode 680 Python Solution
- Pattern
- Two Pointers
- Topics
- Greedy, Two Pointers, String
- 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
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
- Time
- O(n)where n is the length of the string s
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0125 | Valid Palindrome | Easy |
| 0942 | DI String Match | Easy |
| 1147 | Longest Chunked Palindrome Decomposition | Hard |
| 1754 | Largest Merge Of Two Strings | Medium |
| 1850 | Minimum Adjacent Swaps to Reach the Kth Smallest Number | Medium |
| 2193 | Minimum Number of Moves to Make Palindrome | Hard |
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.