def is_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True print(is_palindrome("A man, a plan, a canal: Panama"))
The code uses two pointers moving inward, skipping non-alphanumeric characters and comparing characters case-insensitively. The input string is a well-known palindrome phrase ignoring punctuation and case, so the function returns True.
def is_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True print(is_palindrome("race a car"))
The function returns False because "race a car" is not a palindrome when ignoring spaces and case. The characters compared at the mismatch cause the function to return False.
def is_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 while left <= right: if not s[left].isalnum(): left += 1 if not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True print(is_palindrome("No lemon, no melon"))
The code increments left and right pointers without using 'while' loops to skip non-alphanumeric characters properly. This can cause pointers to move past each other and cause IndexError when accessing s[left] or s[right].
def is_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True print(is_palindrome("") )
An empty string is considered a valid palindrome. The function returns True immediately because the while loop condition is false initially.
The two-pointer technique moves inward from both ends, skipping non-alphanumeric characters and comparing characters in one pass, making it efficient with O(n) time complexity.