LeetCode #125: Valid Palindrome — Another classic two-pointer problem.
A string is a palindrome if it reads the same forwards and backwards, considering only alphanumeric characters and ignoring case.
Examples:
💭 Your turn! Take what you learned above and write the code yourself. Struggling is part of learning! 🧠
Complexity: Time O(n), Space O(1) — no extra string created!
def isPalindrome(s):
left, right = 0, len(s) - 1
while left < right:
# Skip non-alphanumeric
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
# Compare
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return True
isPalindrome("A man, a plan, a canal: Panama")
True
isPalindrome("race a car")
False
isPalindrome(" ")
True