Skip to problem
←

Valid Palindrome II

Easy 0 attempts

You're given a string s. Report true if removing no more than one character from it can turn it into a palindrome.

The string is made up solely of lowercase letters, and a string that's already a palindrome also counts — you're allowed to delete zero characters.

A palindrome reads the same forward and backward. Delete a character at any position while keeping the order of the remaining characters; replacing or rearranging characters is not allowed. Return only a boolean.

For "abca", deleting either b or c works. For "abc", every single deletion leaves two different characters, so return false.

Function contract

Implement validPalindrome(s).

Output: Return true if deleting zero or one character can make s a palindrome; otherwise return false.

Example 1

Input
s = "abca"
Output
true

Example 2

Input
s = "abc"
Output
false
Constraints
  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters

Use two pointers from both ends moving inward. When a mismatch is found, try skipping either the left or right character and check if the remaining substring is a palindrome. If either works, return true.

At the first mismatch, any successful single deletion must remove one of those two mismatching characters. The helper checks the resulting interval without allowing another deletion. Matching outer characters have already been checked and need no further work.

javascript
function validPalindrome(s) {
  function isPalin(left, right) {
    while (left < right) {
      if (s[left] !== s[right]) return false;
      left++;
      right--;
    }
    return true;
  }

  let left = 0, right = s.length - 1;
  while (left < right) {
    if (s[left] !== s[right]) {
      return isPalin(left + 1, right) || isPalin(left, right - 1);
    }
    left++;
    right--;
  }
  return true;
}

Time: O(n) — each character is visited at most twice. Space: O(1) — no extra data structures.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript