Valid Palindrome
Difficulty: Easy
Given a string, check whether it reads the same forwards and backwards.
Only letters and digits count. Ignore punctuation, spaces and symbols, and treat uppercase and lowercase as the same letter.
Examples
Input: s = "A man, a plan, a canal: Panama"
Output: true
Stripping out everything except letters and digits, and lowercasing, gives "amanaplanacanalpanama", which reads the same both ways.
Input: s = "race a car"
Output: false
Cleaned up, this is "raceacar" — reversed it's "racaecar", which is different.
Input: s = ".,"
Output: true
There are no letters or digits at all here, so after cleaning it up there's nothing left — and an empty string trivially reads the same both ways.
Constraints
1 <= s.length <= 2 * 10^5
s consists only of printable ASCII characters.
Approach
The simplest way is to build a cleaned-up string (letters and digits only, lowercase) and check whether it equals its reverse. This works, but it allocates new strings just to compare them.
A leaner way builds nothing new. Put one pointer at the start and one at the end, and walk them toward each other, skipping any character that isn't a letter or digit. When both are on "real" characters, compare them ignoring case. Any mismatch means it isn't a palindrome. If the pointers meet without a mismatch, it is.
Solutions
Brute Force — Clean, Then Compare to Reverse
Build a new string of only the lowercased letters and digits, then compare it to its reverse. Easy to follow, but it does extra work building and reversing a second string.
function isPalindrome(s) {
const cleaned = s.toLowerCase().replace(/[^a-z0-9]/g, "");
const reversed = cleaned.split("").reverse().join("");
return cleaned === reversed;
}Time: O(n) · Space: O(n)
Optimal — Two Pointers
Walk one pointer in from each end, skipping any character that isn't a letter or digit. Compare their characters (ignoring case) as they close in on the middle. No extra string is built.
function isPalindrome(s) {
const isAlnum = (c) => /[a-z0-9]/i.test(c);
let left = 0;
let right = s.length - 1;
while (left < right) {
while (left < right && !isAlnum(s[left])) left++;
while (left < right && !isAlnum(s[right])) right--;
if (s[left].toLowerCase() !== s[right].toLowerCase()) {
return false;
}
left++;
right--;
}
return true;
}Time: O(n) · Space: O(1)