Learning Outcome
After this lesson, you should be able to compare a string from both ends while skipping non-alphanumeric characters.
Problem Statement
Given a string, return true if it reads the same forward and backward after converting uppercase letters to lowercase and removing non-alphanumeric characters.
| Input | Output | Why |
|---|---|---|
"A man, a plan, a canal: Panama" | true | After normalization, it becomes amanaplanacanalpanama. |
"race a car" | false | The normalized characters do not match from both ends. |
Brute Force Approach
Build a new normalized string, reverse it, and compare both strings.
This is simple but uses O(n) extra space for the normalized copy and reversed copy.
Optimized Approach
Use two pointers: one at the start and one at the end. Skip non-alphanumeric characters. Compare lowercase versions of the valid characters. If any pair differs, return false.
Exact Pseudocode
left = 0
right = length(s) - 1
while left < right:
while left < right and s[left] is not alphanumeric:
left = left + 1
while left < right and s[right] is not alphanumeric:
right = right - 1
if lowercase(s[left]) != lowercase(s[right]):
return false
left = left + 1
right = right - 1
return true
Reference Code
class Solution:
def isPalindrome(self, s):
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 TrueSample Dry Run
| left char | right char | Action |
|---|---|---|
| A | a | Lowercase match, move inward |
| space/comma | : | Skip non-alphanumeric characters |
| m | m | Match, continue |
| All valid pairs | match | Return true |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(n) | Each character is visited at most once by a pointer. |
| Space | O(1) | No normalized copy is required. |
Edge Cases
- Only punctuation, such as
"!!!", should returntrue. - Mixed uppercase and lowercase letters.
- Digits mixed with letters.
Interview Checklist
- Confirm the normalization rule.
- Skip invalid characters before comparing.
- Compare lowercase characters.
FAQs
Why not create a cleaned string?
You can, but two pointers avoid extra space.
Are numbers considered valid characters?
In the common version of the problem, yes. Use alphanumeric checks.
What is the core pattern?
Two pointers from both ends.