Skip to content
Problem 680 · LeetCode 680(opens in a new tab)

Valid Palindrome II

EasyStrings

You get a string s of lowercase letters. You may remove at most one letter from it, from any position, or remove nothing.

Return true if what is left reads the same forwards and backwards (a palindrome), and false otherwise.

Example 1

Input:  s = "cbbcc"
Output: true
Why:    remove the c at index 3 to get "cbbc"
2 more examples and the constraints

Example 2

Input:  s = "tacocat"
Output: true
Why:    it is a palindrome already, so remove nothing

Example 3

Input:  s = "mango"
Output: false
Why:    m and o differ, and dropping either one still fails

Constraints

  • 1 ≤ length of s ≤ 100,000
  • s holds only the letters a to z

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every deletionO(n²)
  2. Two pointers, one skipO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 lettersVerdict
Try every deletionO(n²)
Mention it, then move on
Two pointers, one skipO(n)
Best; one walk inward

n = length of the string.

Edge cases to test

  • Already a palindrome. "tacocat" needs no deletion: true.
  • One or two letters. "z" and "qr" are both true; drop either letter of "qr".
  • Only one side works. "cbbcc" needs the right letter removed and "ccbbc" the left one.
  • Two fixes needed. "abcdeba" has c and e out of place: false.

Common mistakes

  • Skipping only one side at the mismatch instead of trying both.
  • Allowing a second skip inside the inner check, which solves a different problem.
  • Copying the string with slices for the inner check, which is still O(n) but wastes memory.

How to talk through it

  1. 1Clarify. Is deleting nothing allowed? Only lowercase letters? Does case or punctuation matter?
  2. 2Give the brute force. Remove each letter and test; O(n²), too slow for 100,000 letters.
  3. 3Find where the fix must go. Matching outer pairs never need a deletion, so the first mismatch is the only place to spend it.
  4. 4Code the two checks. Write a helper that tests s[i..j] in place, then call it with the left or right skipped.
  5. 5Test out loud. Run "cbbcc", "ccbbc" and "abcdeba".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?