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

  1. Normalise: s.toLowerCase().replace(/[^a-z0-9]/g, ""). For international text use Unicode classes: /[^\p{L}\p{N}]/gu and normalize("NFD") to separate accents.
  2. Two pointers: i at the start, j at the end; if s[i] !== s[j] return false; move inwards until they meet.
  3. Return true if 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 be true.
  • Unicode: accented letters and characters outside ASCII.
  • Numbers: 121 is a palindrome; convert with String(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

js
1function isPalindrome(text) {
2 const s = text.toLowerCase().normalize("NFD").replace(/[^\p{L}\p{N}]/gu, ""); // letters and digits only
3 for (let i = 0, j = s.length - 1; i < j; i++, j--) {
4 if (s[i] !== s[j]) return false; // stop at the first mismatch
5 }
6 return true;
7}
8
9// O(1) extra space: skip non-alphanumerics in place
10function 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}
22
23const 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 true
26
27// 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.

Open in study app