Skip junk, compare ends
Walk inward. Ignore anything that is not alphanumeric. Compare lowercased letters. A mismatch is a no; pointers crossing is a yes.
The string is a palindrome iff the filtered character stream reads the same forwards and backwards. Two pointers do that in one pass, no extra copy.
Algorithm
lo,hiat the ends.- Skip non-alphanumeric characters.
- Compare lowercased; mismatch → false. Else step in. Done when
lo >= hi.
- Time
- O(n)
- Space
- O(1)
class Solution: def isPalindrome(self, s: str) -> bool: lo, hi = 0, len(s) - 1 while lo < hi: if not s[lo].isalnum(): lo += 1 continue if not s[hi].isalnum(): hi -= 1 continue if s[lo].lower() != s[hi].lower(): return False lo += 1 hi -= 1 return True