v9.1.1
Menu

Valid Palindrome II

easyPROHash Maps & DesignMeta DSA

Given a string s, return True if s can be a palindrome after deleting at most one character.

Example

Input
aba
Output
True
Reasoning
  • Input: s is the string "aba", a sequence of n=3n = 3 lowercase letters indexed 0,1,20, 1, 2.
  • A string is a palindrome when every character equals its mirror: si=sn−1−is_i = s_{n-1-i} for all ii. For n=3n = 3 the only mirrored pair is positions 00 and 22; the middle letter at position 11 pairs with itself.
  • Here s0=s2=s_0 = s_2 = a, so the pair matches and "aba" is already a palindrome.
  • Deletions used: 00, which satisfies "at most one", so the output is True.
  • Contrast: "abca" has a mismatched inner pair (b vs c), yet deleting the b leaves "aca" and deleting the c leaves "aba"; more than one deletion can work, so it is still True. "abc" mismatches (a vs c), and every one-letter deletion ("bc", "ac", "ab") leaves a non-palindrome, so it is False.
  • Notice that the output only says whether some deletion of at most one letter works, not which letter; and the middle letter of an odd-length string never has to match anything.

Constraints

  • 1 <= len(s) <= 10^5
  • s consists of lowercase English letters

Learn this in

More from Meta DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.