Day 5 - Valid Palindrome

🔍 Problem:

A string is a palindrome if, after converting all uppercase letters to lowercase and removing all non-alphanumeric characters, it reads the same forward and backward.

Given a string s, return True if it’s a valid palindrome, or False otherwise.

🧪 Examples:

Example 1
Input: s = "A man, a plan, a canal: Panama"
Output: True
Explanation: Becomes "amanaplanacanalpanama" — a palindrome.

Example 2
Input: s = "race a car"
Output: False
Explanation: "raceacar" is not the same forward and backward.

Example 3
Input: s = " "
Output: True
Explanation: After cleaning, the string is empty — which is considered a palindrome.

📏 Constraints:

  • 1 <= s.length <= 2 × 10⁵

  • s consists only of printable ASCII characters

🧠 How to Approach It

Step 1: Normalize the input

  • Convert everything to lowercase

  • Remove non-alphanumeric characters

    • You can use isalnum() or a create a list of letters, and check if the char is in the list

Step 2: Check for symmetry

  • Use two pointers (left and right) to compare the string from both ends inward

✅ Python Solution:

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = ''.join(c.lower() for c in s if c.isalnum())
        left = 0
        right = len(s) - 1

        while left < right:
            if s[left] != s[right]:
                return False
            left += 1
            right -= 1

        return True

🧵 TL;DR:

  • ✂️ Strip out anything that's not a letter or number

  • 🔁 Use two pointers to check if the string is symmetric

  • ⚡ Efficient and clean — just like a good palindrome