β 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
l = 0,r = n - 1.- While
l < r:- Move
lright until it points at a letter or digit. - Move
rleft until it points at a letter or digit. - If
lower(s[l]) != lower(s[r]), returnfalse. l++,r--.
- Move
- 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 TrueGot it and submitted?
Mark it solved to earn XP and keep your streak alive.