Two pointers · Easy
Valid palindrome
Ignore non-alphanumeric characters and case. Return whether the string is a palindrome. Compare the letters and digits from the outside in, treating uppercase and lowercase as equal.
Worked example
'A man, a plan, a canal: Panama' → True
- Ignoring spaces, punctuation, and case gives amanaplanacanalpanama.
- Compare the outer a values, then the m values, and continue toward the middle. Every pair matches.
Python solution
def solve(text):
left, right = 0, len(text) - 1
while left < right:
if not text[left].isalnum():
left = left + 1
elif not text[right].isalnum():
right = right - 1
elif text[left].lower() != text[right].lower():
return False
else:
left = left + 1
right = right - 1
return TrueSkip punctuation at both ends and compare inward.
Time: O(n) · Space: O(1)