MediumPythonJavaScriptTypeScript
Strings — Valid Palindrome II
AlgorithmsStringsTwo Pointers
solve(s) — s is made of lowercase letters. Return true if it is a palindrome, or
can become one after deleting at most one character.
Walk two pointers inward from both ends. While the characters match, keep going. On the
first mismatch you have exactly one chance: the answer is true if eithers[left+1..right] or s[left..right-1] is a plain palindrome (skip the left character, or
skip the right one). Checking both is O(n) overall.
Examples
solve("aba") → true
solve("abca") → true // delete "c" (or "b")
solve("abc") → falseSample tests
Test #1Already a palindrome
Input: ["aba"]
Output: true
Test #2One deletion
Input: ["abca"]
Output: true
Test #3Needs two deletions
Input: ["abc"]
Output: false