Back to blog
Sep 05, 2024
4 min read

Valid Palindrome

Check if a string is a palindrome considering only alphanumeric characters and ignoring case.

Difficulty: Easy | Acceptance: 53.20% | Paid: No Topics: Two Pointers, String

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.

Examples

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
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 * 10⁵
s consists only of printable ASCII characters.

Two Pointers

Intuition Use two pointers starting from the beginning and end of the string. Move them towards each other, skipping non-alphanumeric characters, and compare the lowercased characters.

Steps

  • Initialize left pointer at 0 and right pointer at s.length - 1.
  • Loop while left &lt; right.
  • Increment left while it points to a non-alphanumeric character.
  • Decrement right while it points to a non-alphanumeric character.
  • Compare s[left] and s[right] (case-insensitive). If they differ, return false.
  • Move both pointers inward.
  • If the loop finishes, return true.
python
class Solution:
    def isPalindrome(self, s: str) -> bool:
        left, right = 0, len(s) - 1
        while left < right:
            while left < right and not s[left].isalnum():
                left += 1
            while left < right and not s[right].isalnum():
                right -= 1
            if s[left].lower() != s[right].lower():
                return False
            left += 1
            right -= 1
        return True

Complexity

  • Time: O(n)
  • Space: O(1)
  • Notes: Optimal solution with constant extra space.

Filter and Reverse

Intuition Create a new string containing only alphanumeric characters converted to lowercase. Check if this new string is equal to its reverse.

Steps

  • Iterate through the original string s.
  • If a character is alphanumeric, convert it to lowercase and append it to a new string cleaned.
  • Reverse the cleaned string.
  • Compare cleaned with its reverse. Return true if equal, false otherwise.
python
class Solution:
    def isPalindrome(self, s: str) -> bool:
        cleaned = "".join(ch.lower() for ch in s if ch.isalnum())
        return cleaned == cleaned[::-1]

Complexity

  • Time: O(n)
  • Space: O(n)
  • Notes: Uses extra space to store the cleaned string, but logic is very simple.