Valid Palindrome - Problem
The Palindrome Challenge
A palindrome is a word, phrase, or sentence that reads the same forward and backward - like "racecar" or "A man, a plan, a canal: Panama". Your task is to determine if a given string is a valid palindrome.
The Rules:
• Convert all uppercase letters to lowercase
• Remove all non-alphanumeric characters (keep only letters and numbers)
• Check if the cleaned string reads the same forward and backward
Example:
Goal: Return
A palindrome is a word, phrase, or sentence that reads the same forward and backward - like "racecar" or "A man, a plan, a canal: Panama". Your task is to determine if a given string is a valid palindrome.
The Rules:
• Convert all uppercase letters to lowercase
• Remove all non-alphanumeric characters (keep only letters and numbers)
• Check if the cleaned string reads the same forward and backward
Example:
"A man, a plan, a canal: Panama" becomes "amanaplanacanalpanama" which is indeed a palindrome!Goal: Return
true if the processed string is a palindrome, false otherwise. Input & Output
example_1.py — Basic Palindrome
$
Input:
s = "A man, a plan, a canal: Panama"
›
Output:
true
💡 Note:
After removing non-alphanumeric characters and converting to lowercase, we get "amanaplanacanalpanama", which reads the same forward and backward.
example_2.py — Not a Palindrome
$
Input:
s = "race a car"
›
Output:
false
💡 Note:
After cleaning, we get "raceacar". Reading forward: 'raceacar', reading backward: 'raceacar'. Wait, that's wrong - backward is 'racaecar', which is different.
example_3.py — Empty String Edge Case
$
Input:
s = " "
›
Output:
true
💡 Note:
After removing non-alphanumeric characters, we get an empty string, which is considered a palindrome by definition.
Visualization
Tap to expand
Understanding the Visualization
1
Position Inspectors
Place one inspector at the start, another at the end
2
Clean as You Go
Each inspector skips over dust and punctuation
3
Compare Characters
When both find valid letters, they compare (ignoring case)
4
Move Inward
If characters match, both move toward the center
Key Takeaway
🎯 Key Insight: By using two pointers moving inward and comparing characters on-the-fly, we eliminate the need for extra string storage, achieving optimal O(1) space complexity while maintaining O(n) time complexity.
Time & Space Complexity
Time Complexity
O(n)
Single pass through string with two pointers meeting in the middle
✓ Linear Growth
Space Complexity
O(1)
Only using two pointer variables, no additional string storage
✓ Linear Space
Constraints
- 1 ≤ s.length ≤ 2 × 105
- s consists only of printable ASCII characters
- Empty string after cleaning is considered a valid palindrome
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code