function isPalindrome(s) {
let left = 0, right = s.length - 1;
while (left < right) {
while (left < right && !/[a-z0-9]/i.test(s[left])) left++;
while (left < right && !/[a-z0-9]/i.test(s[right])) right--;
if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
left++;
right--;
}
return true;
}
console.log(isPalindrome("A man, a plan, a canal: Panama"));The code uses two pointers moving inward, skipping non-alphanumeric characters. It compares characters in lowercase. The input string is a famous palindrome phrase, so the function returns true.
function isPalindrome(s) {
let left = 0, right = s.length - 1;
while (left < right) {
while (left < right && !/[a-z0-9]/i.test(s[left])) left++;
while (left < right && !/[a-z0-9]/i.test(s[right])) right--;
if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
left++;
right--;
}
return true;
}
console.log(isPalindrome("race a car"));The string "race a car" is not a palindrome when ignoring spaces and case, so the function returns false.
The two-pointer method compares characters from the start and end moving inward, which is efficient because it stops early if mismatch is found and only needs to check half the string.
function isPalindrome(s) {
let left = 0, right = s.length - 1;
while (left < right) {
while (left < right && !/[a-z0-9]/i.test(s[left])) left++
while (left < right && !/[a-z0-9]/i.test(s[right])) right--;
if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
left++;
right--;
}
return true;
}
console.log(isPalindrome("A man, a plan, a canal: Panama"));JavaScript automatically inserts semicolons in many cases, so missing semicolon after left++ does not cause an error. The code runs correctly and returns true.
By expanding around each character and between characters with two pointers moving outward, you can count all palindromic substrings efficiently in O(n²) time.
