PracticeNeetCode ↗LeetCode ↗
Given a string s, determine whether it reads the same forward and backward once you lowercase it and strip out everything that isn't a letter or digit.
left = 0, right = len(s) - 1.left < right: advance left past any non-alphanumeric character, and pull right back past any non-alphanumeric character.s[left].lower() to s[right].lower() — if they differ, return False.left forward and right backward, and repeat until the pointers meet; return True.Time: O(n) — Space: O(1)
def isPalindrome(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 TrueHow the solution above works, piece by piece.
left, right = 0, len(s) - 1: compare from both ends toward the middle; no cleaned copy of the string is built, so O(1) extra space.while loops skip anything that isn't a letter or digit (isalnum()): spaces, punctuation. The left < right guard stops them running past each other.s[left].lower() != s[right].lower(): compare ignoring case. One mismatch means it can't be a palindrome.True. Each character is visited once: O(n).Running it on s = "Was it a car or a cat I saw?":
? (dimmed) are skipped by the inner loops, and W vs w match because both sides are lower-cased.