Why they ask this: Tests the two-pointer technique and careful handling of edge cases like spaces and punctuation.
Problem
A phrase is a palindrome if, after converting all letters to lowercase and removing every non-alphanumeric character, it reads the same forwards and backwards. Return true if the string s is a palindrome, otherwise false.
Example 1
text
Input: "A man, a plan, a canal: Panama"
Output: true // "amanaplanacanalpanama"Example 2
text
Input: "race a car"
Output: false // "raceacar"Example 3
text
Input: " "
Output: true // empty string after cleaningHints
Approach
- Lowercase the string and remove everything except
a-zand0-9. - Put
leftat the start andrightat the end. Whileleft < right, if the characters differ returnfalse; otherwise move both pointers inwards. - If the loop finishes, return
true.
Follow-up: you can avoid the cleaned copy (O(1) extra space) by skipping non-alphanumeric characters with the pointers directly on the original string.
Solution
js
function isPalindrome(s) {
const clean = s.toLowerCase().replace(/[^a-z0-9]/g, '');
let left = 0;
let right = clean.length - 1;
while (left < right) {
if (clean[left] !== clean[right]) return false;
left++;
right--;
}
return true;
}
console.log(isPalindrome('A man, a plan, a canal: Panama')); // true
console.log(isPalindrome('race a car')); // false Time
O(n) Space O(n)Can you explain this in your own words?