Feature image

Valid Palindrome – Leetcode | TypeScript Solution

In my previous post where I discussed about the two sum problem, I told that the solution for the Valid Palindrome and anagram are somewhat similar. However, the palindrome is much more easier than anagram. In this problem, we have to know if a phrase is a palindrome or not. For those who do not know what is Palindrome, “A phrase is a palindrome if  it reads the same forward and backward, after removing all the spaces and non-alphanumeric characters and it shouldn’t be case sensitive. “

From the definition, we can understand couple of things

  1. We have to transform the given text to either lowercase or uppercase
  2. We have to remove all the spaces
  3. We only need to get the words no extra non alpha characters


So we will first transformed all the characters to lowercase by using a lodash function called lowerCase. Once that is done, we will remove all the spaces by writing the below code

 const removedSpaces = lowerCase.split(' ').join('');

Once that is done now we have to remove all the extra non-alphanumeric characters. I was looking at the lodash library with does have a very good function called words. I really liked the functionality so I used that one. Now that I have removed all the clutter, all I have to do is to reverse the original string and check if the original and the reversed string are same. I have wrote the whole code in TypeScript and added it below.

Solution

Solution for the Valid Palindrome
Solution for the valid palindrome

Hello readers, If you are like me who wants to get better at coding, please check out my other blog posts where I solve other leetcode problems.

In the next post, I am going to solve 3Sum problem. You can also check out my other blog post as well.

1 thought on “Valid Palindrome – Leetcode | TypeScript Solution”

  1. Pingback: Two Sum - Leetcode Solution using JavaScript - Al Fahim

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.