Palindrome Check

Easy

Given a string s, determine if it is a palindrome. A palindrome reads the same forward and backward. Consider only alphanumeric characters and ignore cases.

Examples

InputOutput
s = "A man, a plan, a canal: Panama"true
s = "race a car"false

Python Solution

def is_palindrome(s: str) -> bool:
    left, right = 0, len(s) - 1
    while left < right:
        if not s[left].isalnum():
            left += 1
            continue
        if not s[right].isalnum():
            right -= 1
            continue
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

JavaScript Solution

function isPalindrome(s) {
  let left = 0, right = s.length - 1;
  while (left < right) {
    if (!/\w/.test(s[left])) { left++; continue; }
    if (!/\w/.test(s[right])) { right--; continue; }
    if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
    left++;
    right--;
  }
  return true;
}

Step-by-Step Explanation

  1. Use two pointers at the start and end of the string.
  2. Skip non-alphanumeric characters by moving pointers.
  3. Compare characters (case-insensitive) at both pointers.
  4. If they differ, return false. Otherwise move inward and continue.

Complexity Analysis

TimeO(n)
SpaceO(1)

Tags

StringTwo Pointers

Related Problems

Related Tools

All Problems