Valid Palindrome
Difficulty: Easy · Pattern: Two Pointers · LeetCode #125
A phrase is a palindrome if, after converting letters to lowercase and removing everything that isn't a letter or digit, it reads the same forwards and backwards. Given a string s, return whether it's a palindrome.
Examples
text
"Never odd or even" → true ("neveroddoreven")
"Step on no pets!" → true
"race a car" → false
" " → true (empty after cleaning)Hints
- You could build a cleaned string and compare it with its reverse, but that costs O(n) extra space.
- Put pointers at both ends; skip characters that aren't alphanumeric.
- Compare lowercase versions; on a mismatch, return false.
Approach
Use l from the left and r from the right. Advance l past non-alphanumeric characters, and retreat r likewise. Compare the lowercase characters; if they differ, it isn't a palindrome. Otherwise move both inward. When the pointers meet, every pair matched.
Complexity
Time: O(n). Space: O(1).
Python solution
def isPalindrome(s):
l, r = 0, len(s) - 1
while l < r:
while l < r and not s[l].isalnum():
l += 1
while l < r and not s[r].isalnum():
r -= 1
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
return TrueJavaScript solution
function isPalindrome(s) {
const ok = (c) => /[a-z0-9]/i.test(c);
let l = 0, r = s.length - 1;
while (l < r) {
while (l < r && !ok(s[l])) l++;
while (l < r && !ok(s[r])) r--;
if (s[l].toLowerCase() !== s[r].toLowerCase()) return false;
l++; r--;
}
return true;
}