DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

LeetCode 125: Valid Palindrome — Step-by-Step Visual Trace

Easy — Two Pointers | String | Palindrome

The Problem

Determine if a given string is a valid palindrome, considering only alphanumeric characters and ignoring cases. A palindrome reads the same forward and backward.

Approach

Use two pointers starting from both ends of the string, moving inward while skipping non-alphanumeric characters. Compare characters in lowercase at each position until pointers meet or a mismatch is found.

Time: O(n) · Space: O(1)

Code

class Solution:
    def isPalindrome(self, 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
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)