Valid Palindrome
LeetCode 125 · Easy · solution, intuition & step-by-step walkthrough
Two pointers that skip non-alphanumerics.
This is how I solved Valid Palindrome (LeetCode 125), an easy problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Compare characters from both ends, skipping anything that isn't a letter or digit and ignoring case. Any mismatch means it's not a palindrome.
Approach
- 1
left at 0, right at the end.
- 2
Move each pointer past non-alphanumeric characters.
- 3
Compare lower-cased characters; mismatch → False.
- 4
Step both inward until they meet.
How I solved it
Two pointersPythonO(n) time · O(1) space
class Solution:
def isPalindrome(self, s: str) -> bool:
left=0
right=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
Valid Palindrome — FAQ
What is the intuition behind Valid Palindrome?
Compare characters from both ends, skipping anything that isn't a letter or digit and ignoring case. Any mismatch means it's not a palindrome.
How do you solve Valid Palindrome (LeetCode 125)?
1. left at 0, right at the end. 2. Move each pointer past non-alphanumeric characters. 3. Compare lower-cased characters; mismatch → False. 4. Step both inward until they meet.
What is the time and space complexity of Valid Palindrome?
Time: O(n). Space: O(1). (Accepted approach: Two pointers.)
What are common mistakes in Valid Palindrome?
Keep the left < right guard inside the skip loops so they can't cross.