Valid Palindrome II | Delete at Most One Character to Make it a Palindrome

In this tutorial, I am going to discuss a variation of palindrome questions valid palindrome II. In this problem, we can remove a character from a string to make it a palindrome.

Given a non-empty string, We may delete at most one character from a string. We have to write a code which checks whether we can make this string palindrome or not.

For example –

Example 1:

Input : “aba”
Output: true

This string is already palindrome. So we return true.

Example 2:

Input : “abca”
Output: true

This string is not a palindrome. But, if we delete either a character b or c from this string then the new string is a palindrome.

Valid Palindrome II

This problem is the trickiest version of valid palindrome problem. The tricky part is, if the given string is not a palindrome, then we can delete at most one character from a string. After deleting a character we have to check whether a new string is a palindrome or not.

Palindrome

palindrome is a word, phrase or sequence that reads same backwards as forwards. For example – Nitin, madam, etc.

Let’s discuss how we can approach this problem.

Programming video tutorials

Valid Palindrome II Video Tutorial

Valid Palindrome II – Java Code

The idea here is to traverse a string from both the ends using two pointers. Let’s say the two variables are left and right. The initial values of left and right are 0 and string length minus one.

Then run a loop and start comparing characters present at left and right index. If characters are equal then increment left pointer and decrement right pointer. If it is not equal then check whether a string is palindrome by deleting either the character present at left or right index.

If it’s not equal then return false, else return true.

The time complexity of this approach is O(n) and it’s space complexity is O(1).

Sort characters by frequency

Valid Palindrome II Video Tutorial

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.