Skip to content

Palindrome

A palindrome reads the same from left to right and right to left. For example, racecar is a palindrome and hello is not.

Before coding, clarify whether uppercase letters, spaces, and punctuation should count. The first two solutions below compare the string exactly as given.

function isPalindrome(str) {
return str === str.split('').reverse().join('');
}
console.log(isPalindrome('racecar')); // true
console.log(isPalindrome('hello')); // false

This reverses a copy of the string and compares it with the original. It is short and easy to explain. For a string of length n, it uses O(n) time and O(n) extra space.

Place one pointer at each end. Compare the characters, then move inward. A mismatch means the string is not a palindrome.

function isPalindrome(str) {
let left = 0;
let right = str.length - 1;
while (left < right) {
if (str[left] !== str[right]) return false;
left++;
right--;
}
return true;
}

For racecar, the comparisons are r/r, a/a, and c/c. No mismatch is found. This approach uses O(n) time and O(1) extra space for the exact comparison.

If the input A man a plan a canal Panama should pass, normalize it first:

function isPalindromeIgnoringFormatting(str) {
const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, '');
let left = 0;
let right = cleaned.length - 1;
while (left < right) {
if (cleaned[left] !== cleaned[right]) return false;
left++;
right--;
}
return true;
}
console.log(isPalindromeIgnoringFormatting('A man a plan a canal Panama')); // true

The regular expression keeps ASCII letters and digits. Normalizing creates a new string, so this version uses O(n) extra space even though its comparison uses two pointers.

Start with the reverse string solution when a clear answer is enough. Then explain that two pointers keep the same O(n) time while reducing extra space for an exact comparison. Ask about spaces and case before adding normalization.

What should an empty string return? Both exact comparison implementations above return true, because no mismatched pair exists. Decide whether that matches the problem’s requirements before changing the code.