Palindrome Detection with Text Reversal

Learn how to detect palindromes using string reversal. Understand what palindromes are, how to normalize text for comparison, and common palindrome algorithms.

Algorithms

Detailed Explanation

What Is a Palindrome?

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. String reversal is the most intuitive way to detect palindromes.

Simple Palindrome Check

function isPalindrome(str) {
  const reversed = [...str].reverse().join("");
  return str === reversed;
}

Common Palindromes

Words: racecar, level, madam, radar, civic, kayak, rotor, noon, deed

Phrases (ignoring spaces and case):

  • "A man a plan a canal Panama"
  • "Was it a car or a cat I saw"
  • "Never odd or even"
  • "Do geese see God"

Normalization

For phrase palindromes, you need to normalize the text before comparing:

function isPalindromePhrase(str) {
  const normalized = str.toLowerCase().replace(/[^a-z0-9]/g, "");
  const reversed = [...normalized].reverse().join("");
  return normalized === reversed;
}

Steps:

  1. Convert to lowercase
  2. Remove all non-alphanumeric characters
  3. Compare with the reversed version

Efficient Palindrome Check (Without Full Reversal)

You do not always need to reverse the entire string. A two-pointer approach is more efficient:

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

This approach is O(n) time and O(1) space — it checks characters from both ends without creating a new string.

Types of Palindromes

  • Character palindrome: "racecar" (exact character reversal)
  • Word palindrome: "Is it crazy how saying sentences backwards creates backwards sentences saying how crazy it is"
  • Numeric palindrome: 12321, 1001, 9999

Use Case

Palindrome detection is a staple of coding interviews and competitive programming. It appears in problems on LeetCode, HackerRank, and CodeSignal. It is also used in bioinformatics for DNA sequence analysis, where palindromic sequences play a role in restriction enzyme recognition.

Try It — Reverse Text

Open full tool