Given a string s, return true if the s can be palindrome after deleting at most one character from it.

Input: s = "aba"
Output: true
Input: s = "abca"
Output: true
Explanation: You could delete the character 'c' or 'b'.
Input: s = "abc"
Output: false
Constraints:

Contents

In this approach, we will use two pointers start to point beginning of the string and end to point at the end of string, and check whether the string s has palindrome properties or not by removing one character either on left side or right side.

Implementation steps:
public class ValidPalindromeII { static boolean validPalindrome(String s) { int start = 0; int end = s.length() -1; int charsDeletedOnLeft = 0; int charsDeletedOnRight = 0; while(start < end) { if(s.charAt(start) == s.charAt(end)) { start++; end--; } else { if(charsDeletedOnRight ==0) { end--; // try removing the right side character charsDeletedOnRight++; } else if(charsDeletedOnLeft ==0) { end++;// move back since we have already tried removing one character above start++; charsDeletedOnLeft++; } else { return false; } } } return true; } public static void main(String[] args) { System.out.println(validPalindrome("race a car")); System.out.println(validPalindrome(" ")); System.out.println(validPalindrome("aba")); System.out.println(validPalindrome("abca")); System.out.println(validPalindrome("abc")); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the input string length.
Space complexity: O(1).

Above implementations source code can be found at GitHub link for Java code