Valid Palindrome

Valid palindrome.

Given an input string. We have to write a code to check if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For this problem, consider the empty string as a valid palindrome.

For Example –

Example 1:

Input: “A man, a plan, a canal: Panama”
Output: true

Explanation: After removing non-alphanumeric characters, the string is amanaplanacanalpanama. So, it’s a palindrome

Example 2:

Input: “race a car”
Output: false

Before solving this problem, Let’s first understand what is Palindrome?

Palindrome

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

We have to consider two important points while solving this problem. First, we have to consider only alphanumeric characters and second, we have to ignore cases when we compare two characters.

Also, at the end of this post, I have shared a video tutorial link to this problem. We have discussed the problem statement. Let’s discuss how we can solve this problem.

Programming questions on string

Valid palindrome video tutorial

Another variation of this problem is valid palindrome ii.

Valid Palindrome – Java Code

We can solve this problem using two pointers. The idea here is to traverse a string from both ends using two pointers. Here are the steps:

  1. Declare two variables start and end. Initialize start and end variables with 0 and string length minus one.
  2. Run a loop and start comparing characters present at the start and end index. We have to compare characters only if it is alphanumeric. To ignore the case let’s convert them into lowercase.
  3. If both the characters are not equal then return false, else increment the value of start variable and decrement the value of end variable.

The time complexity of this approach is O(n) and its space complexity is O(1).

Check if a string is subsequence of another string

Valid palindrome 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.