Solving Neetcode 150 problems(Today’s problem :-Valid Palindrome)

Tejas Khartude
2 min readJan 22, 2023

--

We are going to start solving Neetcode 150 problems which are important in cracking the interviews MAANG companies. Today, we are going to check whether the given string palindrome or not. The programming language that we are going to use is Python.

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
class Solution(object):

def isPallindrome(self, s):
# Remove special characters and spaces
clean_string = ''.join(e for e in s if e.isalnum())
# Convert to lowercase
clean_string = clean_string.lower()
# Compare the cleaned string to its reverse
return clean_string == ''.join(reversed(clean_string))


if __name__ == "__main__":
s = "A man, a plan, a canal: Panama"
print(Solution().isPallindrome(s)). # Output is True

Explanation :-

This code defines a function called is_palindrome() which takes a string as an input and returns a Boolean value indicating whether the input is a palindrome or not.

The first step in the function is to remove all special characters and spaces from the input string using a list comprehension. The list comprehension iterates through each character in the string and checks if it is alphanumeric (i.e., a letter or a number) using the isalnum() method. If the character is alphanumeric, it is added to a new string called clean_string. This results in a cleaned version of the input string that only contains letters and numbers.

Next, the function converts the clean_string to lowercase using the lower() method, so that the comparison is not case-sensitive.

Finally, the function compares the cleaned and lowercased string to its reverse. The clean_string is compared to its reverse using the join() method with the reversed() function. The reversed() function returns an iterator that generates the items of the input iterable in reverse order, and the join() method concatenates all of the items in the reversed iterator into a single string. If the cleaned and lowercased string is the same as this reversed string, then it is a palindrome and the function returns True. Otherwise, it returns False.

Follow me on GitHub here

I am going to solve all these Neetcode 150 questions and I hope it benefits to you all too. Good luck for your interviews , Happy Coding :)

--

--

Tejas Khartude

Well, I work with Android using Kotlin and Java. I have developed keen interest in Python.