Given a string, the task is to check whether it is a palindrome. A palindrome is astringthat reads the same forward and backward.For example, "madam" is a palindrome, while "hello" is not.
Using Two Pointer Technique
This method compares characters from both ends moving toward the center. It is the most efficient because it checks only half of the string without creating extra copies.
Pythons="malayalam"i,j=0,len(s)-1is_palindrome=Truewhilei<j:ifs[i]!=s[j]:is_palindrome=Falsebreaki+=1j-=1ifis_palindrome:print("Yes")else:print("No")Explanation:
- while loopcompares characters from both ends towards the center as long as i < j.
- if no mismatch is found, the pointers move inward for the next comparison
- After the loop, it prints "Yes" if is_palindromeis True, otherwise "No".
Using all() with Generator Expression
This method checks if all mirrored characters are equal using a generator expression. The string is a palindrome if all comparisons pass.
Pythons="malayalam"ifall(s[i]==s[-i-1]foriinrange(len(s)//2)):print("Yes")else:print("No")Explanation:
- range(len(s)//2) generates indices for the first half of the string.
- s[-i-1] accesses characters from the end of the string.
- s[i] == s[-i-1] checks equality for mirrored positions.
- all() returns True only if every comparison is True.
Using Slicing
This method reverses the string usingslicing(s[::-1]) and compares it with the original string. If both match, the string is a palindrome.
Pythons="malayalam"ifs==s[::-1]:print("Yes")else:print("No")Explanation: It compares the string s with its reverses[::-1]. If they are equal, it prints "Yes" otherwise, it prints "No".
Using reversed() + join()
This method creates a reversed version of the string usingreversed() andjoin(), then compares it with the original string. If they match, it is a palindrome.
Pythons="geeks"rev=''.join(reversed(s))ifs==rev:print("Yes")else:print("No")Explanation: It creates a reversed version of the string with''.join(reversed(s)) and compares it with the original string. If they are equal, it prints "Yes" otherwise, it prints "No".
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice