THN Interview Prep

125. Valid Palindrome

At a Glance

  • Topic: String
  • Pattern: Two Pointers
  • Difficulty: Easy
  • LeetCode: 125

Problem Statement

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " " Output: true Explanation: s is an empty string "" after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome.

Constraints:

1 <= s.length <= 2 * 105
s consists only of printable ASCII characters.

Approach & Solution Steps

Use two pointers, one at the beginning and one at the end. Move them towards the center, skipping non-alphanumeric characters, and comparing the characters at each step.

Optimal JS Solution

function isPalindrome(s) {
  let left = 0, right = s.length - 1;
  const isAlphanumeric = (c) => /^[a-z0-9]+$/i.test(c);
  while (left < right) {
    if (!isAlphanumeric(s[left])) left++;
    else if (!isAlphanumeric(s[right])) right--;
    else if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
    else { left++; right--; }
  }
  return true;
}

Edge Cases & Pitfalls

  • Always consider empty or null inputs.
  • Watch out for off-by-one index errors.

Mark this page when you finish learning it.

Last updated on

Spotted something unclear or wrong on this page?

On this page