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