Code Logo

Valid Palindrome II

Published at05 Jan 2026
Palindrome Easy 22 views
Like23

Given a string s, determine if it can become a palindrome by deleting at most one character. Return true if the string is already a palindrome or can become one by removing a single character, false otherwise.

For example, "aba" is already a palindrome — return true. "abca" can become "aba" by deleting 'c' — return true. "abc" cannot become a palindrome by deleting one character — return false. An empty string or single character returns true.

This problem extends the classic palindrome check by allowing one deletion. It tests two-pointer techniques with a tolerance for a single mismatch. When a mismatch is found, you must check both possibilities: deleting the left character or deleting the right character.

The solution uses two pointers from both ends. When characters differ, it checks two substrings: one skipping the left character and one skipping the right character. If either substring is a palindrome, the original string can be made valid with one deletion.

Edge cases include an empty string (true), a single character (true), a string that is already a palindrome (true), and a string that needs exactly one deletion (check both skip options).

Example Input & Output

Example 1
Input
s = "aba"
Output
true
Explanation

Already a palindrome.

Example 2
Input
s = "abca"
Output
true
Explanation

You can delete u0027cu0027 to get "aba".

Algorithm Flow

Recommendation Algorithm Flow for Valid Palindrome II
Recommendation Algorithm Flow for Valid Palindrome II

Solution Approach

Use two pointers and allow one mismatch by checking both skip possibilities.

function validPalindrome(s)
  i = 0, j = length(s) - 1
  while i < j
    if s[i] != s[j]
      return isPalindrome(s, i + 1, j) or isPalindrome(s, i, j - 1)
    i = i + 1, j = j - 1
  return true

Use two pointers from both ends. When characters match, move both pointers inward. When a mismatch occurs, check if skipping either the left character (i+1 to j) or the right character (i to j-1) produces a palindrome. Use a helper to check palindrome over a substring range.

Time complexity is O(n), space complexity is O(1).

Best Answers

java
import java.util.stream.*;class Solution{public String even_numbers_as_string(Object nums){int[] a=(int[])nums;return IntStream.of(a).filter(x->x%2==0).mapToObj(String::valueOf).collect(Collectors.joining(","));}}