One of the most basic and commonly asked interview questions is to check whether a string is a palindrome or not using python. A palindrome is a string or a number that, if we reverse, equals the original value. For example- if we reverse the string MALAYALAM, we will get back the original string. Also, if we reverse the number 12321, we will get 12321 back. These are known as palindromes.
In this article, we will learn how to check whether a string or a number is a palindrome or not in many different ways. In addition to it, we will solve some fun questions which are commonly asked in competitions and interviews.
Checking Whether a String is a Palindrome in Python
We can use the concept of slicing to reverse the string, and then we can check whether the reverses string is equal to the original string or not.
def check_palindrome(string): # transversing the string from last to first reversed_string=string[::-1] if string==reversed_string: print(string, "is a palindrome") else: print(string, "is not a Palindrome")
if name=='main': check_palindrome("RADAR") check_palindrome("PythonPool") Output- RADAR is a palindrome PythonPool is not a Palindrome
The above method is straightforward to use and also a good method, and you can use it in competitions, but people generally don’t prefer to use it in interviews. This method is so simple, and people prefer to code from scratch to make this kind of program to show their skills. We will study that approach too in the following section.
By Using for Loop
def is_palindrome(string): reversed_string="" # transversing through string from last for i in range(len(string),0,-1): # Addind last characters of string into a new string reversed_string+=string[i-1] if string==reversed_string: print("Palindrome") else: print("Not a palindrome")
if __name__==__'main'__: is_palindrome("racecar") is_palindrome("Python") Output- Palindrome Not a palindrome
Using reversed() function
string="MALAYALAM" # joining characters of reversed string one by one reversed_string = ''.join(reversed(string)) if reversed_string==string: print(string," is Palindrome") else: print(string,"Not a Palindrome") Output- MALAYALAM is Palindrome
Using While Loop
def check_palindrome(string): l= len(string) first = 0 last = l-1 isPalindrome=True # ensuring that we do not iterate through more than half # of the list while(first<last): # if the first character is same as last character keep # moving further if(string[first]==string[last]): first=first+1 last=last-1 # if the characters at first and last do not match break # the loop else: isPalindrome=False break return isPalindrome string="MADAM" isPalindrome=check_palindrome(string) if(isPalindrome): print("It is a palindrome ") else: print("Not a Palindrome") Output- It is a palindrome
Checking Whether a Number is a Palindrome in Python
Using while loop
We are going to use the following concept-
The remainder of this number, when divided by 10, is:
Then, we will divide the number by 10.
number=12321 reverse_number=0 n=number # while we have not reached the end of the number while(n !=0): # finding the last element of number 'n' rem = n % 10 reverse_number = reverse_number * 10 + rem n=int(n / 10) if(number == reverse_number): print("Palindrome") else: print("Not a Palindrome") Output- Palindrome
We can also first convert the number into a string and then apply any of the methods above to check if the number is palindrome or not.
number=12321 # converting the number to string and then reversing it if str(number)[::-1]==str(number): print("Number:",number," is a Palindrome") else: print("Number:",number," is not a Palindrome") Output- Number: 12321 is a Palindrome
Checking Whether a Phrase is a Palindrome in Python
Checking if a phrase is a palindrome or not is different from checking if a word is a palindrome or not. So, we cannot apply any of the above methods for a phrase.
For example- The phrase ‘Too hot to hoot’ is a palindrome if you ignore the upper case – lower case and spaces in the characters.
def is_palindrome(string): reversed_string="" # Removing all the spaces s=string.replace(" ","") # making the whole string in lowercase characters s=s.lower() for i in range(len(s),0,-1): if s[i-1] >='a' and s[i-1]<='z': reversed_string+=s[i-1] if s==reversed_string: print("Palindrome") else: print("Not a palindrome") if __name__=='__main__': is_palindrome("Too hot to hoot") is_palindrome("Python") Output- Palindrome Not a palindrome
There are some other types of palindromes, like- ‘Is it crazy how saying sentences backward creates backward sentences saying how crazy it is.’ It is different from other palindromes we have discussed until now because here, if we reverse the characters, it is not a palindrome. But if we reverse it word by word, it is a palindrome.
string='Is it crazy how saying sentences backwards creates backwards sentences saying how crazy it is' string1=string.lower() string1=string.replace(" ","") new_string="" # Wherever there is any space make a list element list1=string1.split(" ") # join the list into string starting from the last reverse="".join(list1[::-1]) reverse_string="" for i in reverse: # adding only characters in the new string if i>='a' and i<='z': reverse_string+=i for i in string1: if i>='a' and i<='z': new_string+=i if new_string==reverse_string: print(string,":Palindrome") else: print(string,":Not a Palindrome") Output- Is it crazy how saying sentences backward creates backward sentences saying how crazy it is: Palindrome
To find the Palindromic longest substring in a string
A very common and interesting question on palindromes is to find the longest substring, which is a palindrome from a string that may or may not be a palindrome. I suggest you try it yourself once and then look at the solution below.
There are many ways to solve this problem. We will go for the easiest one which all of us will be able to understand easily.
m="" s='babad' for i in range(len(s)): # iterating through the string from the last for j in range(len(s),i,-1): # ensuring that we do not iterate through more than half of # the string if len(m)>=j-i: break elif s[i:j]==s[i:j][::-1]: m=s[i:j] print(m) Output- bab
The time complexity for the above program is O(n^2) as we have a for loop inside a for a loop.
We have studied what a palindrome is, how to check whether a string or a number is a palindrome. We have also covered some common interview questions like checking for a phrase if it is a palindrome and finding the longest substring, which is a palindrome in python. I hope you will try each problem, and please comment down if you face any issues in it.