Python 0680.py
class Solution:
def validPalindrome(self, s: str) -> bool:
left = 0
right = len(s) - 1
while left < right and s[left] == s[right]:
left += 1
right -= 1
if left >= right:
return True
# delete one on left side
l, r = left+1, right
while l < r and s[l] == s[r]:
l += 1
r -= 1
if l >= r:
return True
# delete one on right side
l, r = left, right-1
while l < r and s[l] == s[r]:
l += 1
r -= 1
return l >= r
Difficulty
and has an acceptance rate of about 45% (2+ million submissions).
Typical patterns to solve this problem:
- Greedy
- String
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation determines whether a given string can become a palindrome after removing at most one character. It employs a two-pointer technique that scans from both ends toward the center, comparing characters pairwise. When a mismatch is encountered, the algorithm explores the two possible deletions-either the left character or the right character-and checks if the remaining substring forms a palindrome. The function returns True as soon as a valid configuration is found, otherwise it returns False after both deletion attempts have been exhausted.
Initial Two-Pointer Scan
The first loop advances two indices, left and right, while the characters at those positions match. This establishes the longest prefix and suffix that already satisfy the palindrome property.
left = 0
right = len(s) - 1
while left < right and s[left] == s[right]:
left += 1
right -= 1
if left >= right:
return True
If the pointers cross, the original string is already a palindrome and the function terminates early.
Attempt Deleting Left Character
When a mismatch is found, the code assumes the left character might be the one to remove. It creates new pointers l and r that skip the suspect character (left + 1) and then continues the pairwise comparison.
l, r = left + 1, right
while l < r and s[l] == s[r]:
l += 1
r -= 1
if l >= r:
return True
If this inner scan reaches the center without further mismatches, the string becomes a palindrome after deleting the left character, and the function returns True.
Attempt Deleting Right Character
If the left-deletion path fails, the algorithm mirrors the same logic for the right side. It sets the pointers to left and right - 1, effectively ignoring the right character that caused the initial conflict.
l, r = left, right - 1
while l < r and s[l] == s[r]:
l += 1
r -= 1
return l >= r
The final return statement evaluates whether the remaining substring is a palindrome after the right-side deletion. If it is, True is returned; otherwise, False.
Edge Cases Handled
The code gracefully handles strings of length zero or one because the initial pointer positions cause the while condition to fail immediately, leading to left >= right and a True result. It also correctly processes strings that are already palindromes, returning early without performing unnecessary work. For strings where the only discrepancy is at the very ends, the deletion attempts still succeed because the inner loops start from the mismatched positions and quickly converge. Cases with multiple identical characters surrounding a single mismatched pair are also covered, as the inner loops continue scanning past the deletion point until either a second mismatch appears or the pointers meet.
Performance Optimizations
The algorithm avoids constructing new substrings or copying data; it works entirely with index arithmetic, which keeps memory usage minimal. Early exits are placed after each successful palindrome check, preventing the execution of the second deletion attempt when the first already succeeds. The two-pointer scans run in a single pass over the string, and each character is examined at most twice-once in the initial scan and once in one of the deletion attempts-ensuring that the overall work scales linearly with the length of the input.
ELI5 - Simplified Explanation
Imagine you have a long word written on a piece of paper and you want to check if it reads the same way forward and backward, like the word radar. To figure this out, imagine two tiny ants standing at each end of the word. One ant starts at the very first letter on the left, and the other ant starts at the very last letter on the right.
The ants start walking toward each other. Every time they take a step, they look at the letters they are standing on to make sure they match. If the ants meet in the middle and every letter pair matched perfectly, then the word is already a perfect mirror image.
Sometimes, a word is almost a perfect match but has one pesky extra letter causing a problem. When the ants find a letter that does not match, they get to try something special. They can pick one of the two letters they are currently looking at and pretend it is not there.
After one of the ants jumps over that tricky letter, both ants continue walking toward the middle again to see if the rest of the letters match up. If they can finish the walk successfully after skipping just one letter, then the word is a secret success. If they still cannot make it work after skipping a letter on either side, then the word just does not fit the pattern.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | C# | Python | JS | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 125: Valid Palindrome
- problem 1216: Valid Palindrome III
- problem 2330: Valid Palindrome IV
Solved On The Same Day
- problem 478: Generate Random Point in a Circle
- problem 497: Random Point in Non-overlapping Rectangles
- problem 519: Random Flip Matrix
- problem 581: Shortest Unsorted Continuous Subarray
- problem 659: Split Array into Consecutive Subsequences
- problem 738: Monotone Increasing Digits
- problem 743: Network Delay Time
- problem 769: Max Chunks To Make Sorted
- problem 985: Sum of Even Numbers After Queries
- problem 1048: Longest String Chain
- problem 1094: Car Pooling
- problem 1324: Print Words Vertically
- problem 1680: Concatenation of Consecutive Binary Numbers
- problem 1823: Find the Winner of the Circular Game
- problem 1860: Incremental Memory Leak
- problem 1922: Count Good Numbers
- problem 2487: Remove Nodes From Linked List
- problem 381: Insert Delete GetRandom O(1) - Duplicates allowed
- problem 517: Super Washing Machines
- problem 632: Smallest Range Covering Elements from K Lists
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality