← All problems
#125EasyπŸ”’ Pattern ???

Valid Palindrome

Check whether a sentence reads the same forwards and backwards when only letters and digits count and upper/lower case are treated alike.

Try it on LeetCode
πŸ€” GUESS THE PATTERN+5 XP

Before you peek at the solution: which pattern do you think this one uses?

Hints0/3

Optional. Open them one at a time if you're stuck.

🎬 Walkthrough video

Video coming soon

The video is still being edited. Meanwhile, read the explanation and the code.

πŸ“ Explanation

Intuition

A palindrome means the k-th character from the left equals the k-th from the right. So put one pointer at the start, one at the end, compare, and walk them toward each other.

Symbols and spaces don't count. Just skip over them instead of building a new string.

Steps

  1. l = 0, r = n - 1.
  2. While l < r:
    • Move l right until it points at a letter or digit.
    • Move r left until it points at a letter or digit.
    • If lower(s[l]) != lower(s[r]), return false.
    • l++, r--.
  3. If the loop finishes, return true.

Why O(1) memory?

We only keep two indices and never copy the string.

⏱️ Complexity

TimeO(n)
SpaceO(1)

πŸ’» Solution code

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

Got it and submitted?

Mark it solved to earn XP and keep your streak alive.