CodingNeed.
Fresher · Two pointers

Palindrome · Compare from Both Ends

For an ASCII string, ignore non-alphanumeric characters and case. Return whether the remaining characters read the same in both directions. An empty normalized string is a palindrome.

Examples

"A man, a plan, a canal: Panama" → true

Compare approaches

Normalize and reverse

Construct a normalized string and compare it with its reversal.

Time: O(n) · Space: O(n)

function palindrome(text) { const s = text.toLowerCase().replace(/[^a-z0-9]/g, ""); return s === [...s].reverse().join(""); }
Two pointers

Skip punctuation in place and compare only the next valid pair. The ASCII contract avoids Unicode normalization ambiguity.

Time: O(n) · Space: O(1)

function palindrome(text) {
  let left = 0, right = text.length - 1;
  const valid = c => /[a-z0-9]/i.test(c);
  while (left < right) {
    if (!valid(text[left])) { left++; continue; }
    if (!valid(text[right])) { right--; continue; }
    if (text[left].toLowerCase() !== text[right].toLowerCase()) return false;
    left++; right--;
  }
  return true;
}

Common traps

  • Do not compare spaces or punctuation.
  • Define character and case rules before coding.
Practise in the workspace →

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.