Check if a string is a palindrome
Normalise the string (lowercase, keep only letters and digits), then compare characters from both ends moving inwards with two pointers; that is O(n) time and O(1) extra space beyond the normalised string.
Steps
- Normalise:
s.toLowerCase().replace(/[^a-z0-9]/g, ""). For international text use Unicode classes:/[^\p{L}\p{N}]/guandnormalize("NFD")to separate accents. - Two pointers:
iat the start,jat the end; ifs[i] !== s[j]returnfalse; move inwards until they meet. - Return
trueif no mismatch was found.
The one-liner
clean === [...clean].reverse().join("") is readable and fine for most cases, but uses O(n) extra memory and always processes the whole string, while two pointers can stop at the first mismatch.
Skipping without building a new string
For a true O(1) extra-space version, move the pointers past non-alphanumeric characters in place instead of creating a cleaned copy.
Edge cases to mention
- Empty string and single characters are palindromes.
- Case and punctuation:
"A man, a plan, a canal: Panama"should betrue. - Unicode: accented letters and characters outside ASCII.
- Numbers:
121is a palindrome; convert withString(n)(or reverse digits arithmetically).
Follow-ups
"Valid Palindrome II" (can it become a palindrome by deleting at most one character?) and "longest palindromic substring" (expand around centres, O(n²)).
Code example
1function isPalindrome(text) {2 const s = text.toLowerCase().normalize("NFD").replace(/[^\p{L}\p{N}]/gu, ""); // letters and digits only3 for (let i = 0, j = s.length - 1; i < j; i++, j--) {4 if (s[i] !== s[j]) return false; // stop at the first mismatch5 }6 return true;7}89// O(1) extra space: skip non-alphanumerics in place10function isPalindromeInPlace(text) {11 const ok = (c) => /[a-z0-9]/i.test(c);12 let i = 0, j = text.length - 1;13 while (i < j) {14 if (!ok(text[i])) { i++; continue; }15 if (!ok(text[j])) { j--; continue; }16 if (text[i].toLowerCase() !== text[j].toLowerCase()) return false;17 i++;18 j--;19 }20 return true;21}2223const tests = ["racecar", "A man, a plan, a canal: Panama", "hello", "", "No 'x' in Nixon", "éa"];24for (const t of tests) console.log(JSON.stringify(t), isPalindrome(t), isPalindromeInPlace(t));25// all agree, except "éa": false true - the ASCII-only version skips "é" and wrongly says true2627// Follow-up: can it become a palindrome by removing at most one character?28function validPalindromeOneRemoval(s) {29 const isPal = (i, j) => { while (i < j) if (s[i++] !== s[j--]) return false; return true; };30 for (let i = 0, j = s.length - 1; i < j; i++, j--) {31 if (s[i] !== s[j]) return isPal(i + 1, j) || isPal(i, j - 1);32 }33 return true;34}35console.log(validPalindromeOneRemoval("abca"), validPalindromeOneRemoval("abc")); // true false
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.