SDE & MLE Prep

125. Valid Palindrome

Problem

After lowercasing s and dropping every character that isn't a letter or digit, does it read the same forwards and backwards?

Example: "A man, a plan, a canal: Panama" → true; "race a car" → false

Pointers from both ends, skip non-alphanumerics, compare lowercase.

Complexity: O(n) time, O(1) space.

class Solution:
    def isPalindrome(self, s: str) -> bool:
        l, r = 0, len(s) - 1
        while l < r:
            if not s[l].isalnum():
                l += 1
            elif not s[r].isalnum():
                r -= 1
            elif s[l].lower() != s[r].lower():
                return False
            else:
                l, r = l + 1, r - 1
        return True