How do you check if a string is a palindrome in JavaScript?
Quick answer
Normalise the string (lower case, remove non-alphanumeric characters), then compare characters from both ends moving inward with two pointers. This is O(n) time and O(1) extra space beyond the normalised copy.
Problem
Given a string s, return true if it is a palindrome after converting all letters to lower case and removing all non-alphanumeric characters.
Input
Output
Constraints
- 1 ≤ s.length ≤ 2 × 10⁵
- s contains printable ASCII characters
Example
After cleaning, the string is "amanaplanacanalpanama", which reads the same in both directions.
Solution
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;
}
isPalindrome('A man, a plan, a canal: Panama'); // true
isPalindrome('race a car'); // falseLower-case the string and remove anything that is not a letter or digit.
Place one pointer at the start and one at the end.
If the characters differ, it is not a palindrome.
Move both pointers inward until they meet.
Time complexity
Space complexity
Alternative approach
Compare the cleaned string with its reverse. It is shorter to write but allocates extra arrays and strings.
const isPalindrome = (s) => {
const clean = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return clean === [...clean].reverse().join('');
};Discussion
A palindrome reads the same forwards and backwards. Interviewers usually mean a "valid palindrome" that ignores case, spaces and punctuation, so ask before coding.
The shortest solution is s === s.split("").reverse().join(""), which is fine to mention but builds two extra strings. The two-pointer approach shows you understand the problem: compare the first and last characters, move inward, and stop at the first mismatch.
Common mistakes
- Not asking whether case and punctuation should be ignored.
- Forgetting that an empty string counts as a palindrome.