How do you check if a string is a palindrome, ignoring spaces, punctuation and case?
Use two pointers from both ends. Skip characters that are not letters or digits, compare the rest in lowercase, and move inward. If any pair differs, it is not a palindrome.
Explain it simply
A palindrome reads the same forwards and backwards, like "Malayalam". For a sentence such as "A man, a plan, a canal: Panama" the spaces and commas should not count.
Put one finger at each end. If a finger sits on punctuation, slide it inward. When both fingers rest on real characters, compare them. If they match, move both inward; if not, stop.
Example
function isPalindrome(s) {
const isAlnum = (c) => /[a-z0-9]/i.test(c);
let l = 0;
let r = s.length - 1;
while (l < r) {
if (!isAlnum(s[l])) { l++; continue; }
if (!isAlnum(s[r])) { r--; continue; }
if (s[l].toLowerCase() !== s[r].toLowerCase()) return false;
l++;
r--;
}
return true;
}
console.log(isPalindrome("A man, a plan, a canal: Panama")); // Output: true
console.log(isPalindrome("race a car")); // Output: falseComplexity
Time O(n), space O(1).
What to say in the interview
"I use two pointers, skip anything that is not alphanumeric, and compare lowercase characters as I move inward. It is O(n) time and O(1) space. Building a cleaned and reversed copy is simpler but uses O(n) extra memory."
Common mistakes
- Comparing without lowercasing.
- Forgetting that the left and right pointers must both skip punctuation.