Problem 680

Abstract / Summary

You can make a string a palindrome by removing at most one character.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
25 lines | 634 bytes | submitted September 23, 2023 | GitHub   10% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (2+ million submissions).

Typical patterns to solve this problem:
  • Greedy
  • String
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.07 | σ = 0.72

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
41 links | 26 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

21 solutions   September 23, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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