Valid Palindrome
LeetCode 125 • Easy • Two Pointers
Given a string s, determine if it is a palindrome considering only alphanumeric characters and ignoring case.
TimeO(n)each char at most once
SpaceO(1)two pointers
Left: —
Right: —
Result: —
Ready
Press Play. Two pointers converge: skip non-alphanumeric, compare case-insensitive. Return False on mismatch, True if pointers meet.
TimeO(n)same as iterative
SpaceO(n)call stack depth
Recursive: isPal(s, left, right) — base when left ≥ right return True; skip non-alnum; if mismatch return False; recurse with left+1, right-1.
3
Practice until you don't need to look. Use the guide comments below as scaffolding. The green highlights are the nuances to burn into memory.
PATTERN ▸ Two pointers O(n) · O(1)
① INIT POINTERS
left, right = 0, len(s)-1
② LOOP WHILE left < right
while left < right:
③ SKIP NON-ALNUM
while left < right and not s[left].isalnum(): left += 1
while left < right and not s[right].isalnum(): right -= 1
④ COMPARE & ADVANCE
if s[left].lower() != s[right].lower(): return False
left += 1; right -= 1
⑤ RETURN
return True
▼ your implementation ▼
Verify your solution: