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: "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
🪞 The Mirror Text Inspector"A man, a plan, a canal: Panama"👤Left Inspector👤Right InspectorComparison Process✓ 'A' (pos 0) == 'a' (pos 28)✓ 'm' (pos 2) == 'm' (pos 27)✓ 'a' (pos 3) == 'a' (pos 26)🎯 Key Insight: No Extra Storage!Compare characters on-the-fly while moving pointers inwardTime: O(n) | Space: O(1)
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

n
2n
Linear Growth
Space Complexity
O(1)

Only using two pointer variables, no additional string storage

n
2n
Linear Space

Constraints

  • 1 ≤ s.length ≤ 2 × 105
  • s consists only of printable ASCII characters
  • Empty string after cleaning is considered a valid palindrome
Asked in
Meta 45 Amazon 38 Microsoft 32 Google 28 Apple 22
89.5K Views
Very High Frequency
~15 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen