Hiprup

How do you check if a string is a palindrome?

A palindrome reads the same forwards and backwards.

  1. Normalise — lowercase and strip non-alphanumeric characters if needed.

  2. Compare — check the string against its reverse, or use two pointers from both ends moving inward.

Most efficient: the two-pointer approach — O(n) time and no extra string allocation.

// Method 1: Reverse + compare
function isPalindrome(str) {
  const clean = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  return clean === clean.split('').reverse().join('');
}

// Method 2: Two pointers (O(n) time, O(1) space)
function isPalindrome2(str) {
  const clean = str.toLowerCase().replace(/[^a-z0-9]/g, '');
  let left = 0, right = clean.length - 1;
  while (left < right) {
    if (clean[left] !== clean[right]) return false;
    left++;
    right--;
  }
  return true;
}

console.log(isPalindrome('racecar'));           // true
console.log(isPalindrome('A man, a plan, a canal: Panama')); // true
console.log(isPalindrome('hello'));             // false

Both approaches clean the string first (lowercase, remove non-alphanumeric). Reverse: compare string with its reverse.

Two-pointer: compare characters from both ends, moving inward. Two-pointer is more efficient (O(1) space vs O(n) for the reversed string).

Show both approaches: reverse (simple) and two-pointer (efficient). The cleaning step (lowercase + regex) is essential for real-world strings ('A man, a plan...').

Two-pointer is O(n) time, O(1) space (optimal).

How do you check if a string is a palindrome? | Hiprup