Q3: Check if a String is a Palindrome
Clean non-alphanumeric characters and convert to lower case, then use a two-pointer approach moving toward the center to check if the string reads identically forward and backward.
Two-Pointer Palindrome Validation
function isPalindrome(str) {
const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
let left = 0;
let right = cleaned.length - 1;
while (left < right) {
if (cleaned[left] !== cleaned[right]) return false;
left++;
right--;
}
return true;
}
console.log(isPalindrome('A man, a plan, a canal: Panama')); // true💡 Two pointers move inward from opposite ends, allowing early exit as soon as a non-matching character pair is found.
Key Takeaways
- Sanitizes strings using Regular Expressions prior to checking.
- Uses a two-pointer approach to compare characters from opposite ends toward the center.
Knowledge Check
What is the primary benefit of a two-pointer approach over str === str.split('').reverse().join('')?