Full answer
python
def is_palindrome(s):
cleaned = [c.casefold() for c in s if c.isalnum()]
return cleaned == cleaned[::-1]
def is_palindrome_two_pointers(s):
i, j = 0, len(s) - 1
while i < j:
if not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
elif s[i].casefold() != s[j].casefold():
return False
else:
i, j = i + 1, j - 1
return True
for text in ["Never odd or even", "A man, a plan, a canal: Panama!", "Python", ""]:
print(repr(text), is_palindrome(text), is_palindrome_two_pointers(text))Output:
text
'Never odd or even' True True
'A man, a plan, a canal: Panama!' True True
'Python' False False
'' True TrueBoth versions agree on every case. The first builds a cleaned list and compares it with its reverse, which is short and clear but uses extra memory. The second walks inward from both ends, skipping punctuation and spaces, and stops at the first mismatch. An empty string counts as a palindrome, an edge case worth stating. isalnum accepts letters and digits from any script, so the functions also work for non-English text.
python
def is_palindrome(s):
cleaned = [c.casefold() for c in s if c.isalnum()]
return cleaned == cleaned[::-1]
def is_palindrome_two_pointers(s):
i, j = 0, len(s) - 1
while i < j:
if not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
elif s[i].casefold() != s[j].casefold():
return False
else:
i, j = i + 1, j - 1
return True
for text in ["Never odd or even", "A man, a plan, a canal: Panama!", "Python", ""]:
print(repr(text), is_palindrome(text), is_palindrome_two_pointers(text))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Normalise case and drop non-alphanumerics
- Compare with the reverse
- Two pointers use constant extra space
- State edge cases such as empty strings
Common mistakes
- Forgetting punctuation and spaces
- Using lower() where casefold is safer
Follow-ups
- How would you find the longest palindromic substring?
- What is the time complexity of each version?
Tips
- Offer both versions