Leetcode 125: Valid Palindrome

A two-pointer approach to check if a string is a valid palindrome

Original problem is here.

Inward Traversal Two-Pointer Approach

Algorithm

String Handling

cleaned_s = ''.join(c.lower() for c in s if c.isalnum())

Note: While filtering the string upfront is very clean, an optimized solution would do this filtering on the fly during the two-pointer traversal to save $O(n)$ space.

Initialization

Main loop

Termination

My solution

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = [c.lower() for c in s if c.isalnum()]
        s = ''.join(s)

        left = 0
        right = len(s)-1
        while left < right:
            if s[left] == s[right]:
                left += 1
                right -= 1
            else:
                return False
        return True

Complexity Analysis