Algorithm

Palindrome Algorithm

A palindrome reads the same forwards and backwards. "racecar" is one. "A man, a plan, a canal, Panama!" is too — once you strip out spaces and punctuation.

10 Mar 2024

Palindrome Algorithm

A palindrome reads the same forwards and backwards. "racecar" is one. "A man, a plan, a canal, Panama!" is too — once you strip out spaces and punctuation.

The problem

Given a string, determine if it's a palindrome. Ignore case and non-alphanumeric characters.

The clean approach

Strip everything that isn't a letter or number. Lowercase it. Compare from both ends using two pointers.

Javascript
const isPalindrome = (input) => {
    const cleaned = String(input)
        .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;
};

The one-liner (less efficient)

Javascript
const isPalindrome = (input) => {
    const cleaned = String(input).toLowerCase().replace(/[^a-z0-9]/g, "");
    return cleaned === cleaned.split("").reverse().join("");
};

Complexity

Two-pointer approach:

  • Time: O(n) — single pass from both ends.
  • Space: O(n) — for the cleaned string. Could be O(1) if you skip non-alphanumeric characters in place.

Reverse approach:

  • Time: O(n) — but with higher constant factor (split, reverse, join each iterate the string).
  • Space: O(n) — creates multiple intermediate arrays.

Trade-offs

The two-pointer approach is more efficient and exits early on mismatches. The reverse approach is more readable and works great for quick scripts. In an interview, show the two-pointer version — it demonstrates that you understand you don't need to check the whole string once you find a mismatch.

Keep reading