Valid Palindrome | LeetCode 125 | Python | Solution

Click here to see the problem details on LeetCode.

Before solving this problem, we have to know about palindrome. According to the definition of Wikipedia:

A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar.


The problem says that we have to consider alphanumeric characters. If the given string contains any characters which are not alphanumeric, we can ignore them.

Coding Part

This one is a pretty easy problem. There are many ways to solve this problem.

Here, we will create a new string to store all alphanumeric characters from the given string to solve this problem. To check a character is alphanumeric or not, we will use python’s string method isalnum(). Before storing, we will convert it into a lowercase character.

After that, we will compare the new string with its reverse version. If both are similar, we can say it’s a palindrome. Otherwise, not.

Let’s see the code for a better understanding.

class Solution:
    def isPalindrome(self, s: str) -> bool:
        new_str = ''
        for char in s:
            if char.isalnum():
                new_str += char.lower()
        return new_str == new_str[::-1]

That’s all about the problem solution. I hope it will help you.

Scroll to Top