Determine whether a string reads the same forwards and backwards (e.g. "madam", "racecar").
Compare characters from both ends moving inward with two pointers — O(n) time, O(1) extra space. A common follow-up ignores case, spaces, and punctuation (a 'sentence palindrome').
function isPalindrome(s) {
let i = 0, j = s.length - 1;
while (i < j) {
if (s[i] !== s[j]) return false;
i++; j--;
}
return true;
}
// Sentence variant: normalize first
const isClean = (s) => {
const c = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return c === [...c].reverse().join('');
};Palindrome logic appears when validating symmetric tokens, but its real value is demonstrating clean two-pointer traversal and edge-case thinking.
isPalindrome passes for 'madam' but fails 'Race car'. Why, and how do you fix it?