\

Test Palindromicity

Difficulty: N/A | Solved: December 20, 2025

Problem

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.

Brainstorming

we have 2 pointer one at the left end the other at the right end we have a while loop where we iterate from both left and right we check if the current char at the left if its alpha numeric and the current char at the right is alpha numeric if they are we check if they are same if they are not we just move ahead

s = "A man, a plan, a canal: Panama"



def is_valid_palindrom(s:str) -> bool:
	left = 0
	right = len(s) -1
	while left < right:
		if not s[left].isalnum(): # check if the char is not alpha numeric
			left +=1 # move the left pointer 
			continue
		if not s[right].isalnum():# check if the char is not alpha numeric
			right -=1 # move the right pointer
			continue
		if s[left].lower() != s[right].lower():
			return False
		# THE FIX: Always move pointers inward after a successful comparison # to check the next pair. left += 1 right -= 1
		left +=1
		right -=1
	return True	

ideal


def is_valid_palindrom_cleaner(s: str) -> bool:
    left = 0
    right = len(s) - 1
    
    while left < right:
        # Move left pointer until it points to an alphanumeric character
        while left < right and not s[left].isalnum():
            left += 1
            
        # Move right pointer until it points to an alphanumeric character
        while left < right and not s[right].isalnum():
            right -= 1

        # If pointers haven't crossed, compare the characters
        if left < right and s[left].lower() != s[right].lower():
            return False
        
        # Move to the next pair
        left += 1
        right -= 1
        
    return True

# Test cases
print(is_valid_palindrom_cleaner("A man, a plan, a canal: Panama")) # True
print(is_valid_palindrom_cleaner("race a car"))                    # False
print(is_valid_palindrom_cleaner(" "))                             # True