How do you check if a string is a valid palindrome using two pointers in Python?
Posted by JackBrn
Last Updated: August 09, 2024
Checking If a String Is a Valid Palindrome Using Two Pointers in Python
A palindrome is a string that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. The two-pointer technique is an efficient method for determining if a given string qualifies as a palindrome. This approach involves utilizing two pointers: one starting at the beginning of the string and the other at the end.
Steps to Implement the Two-Pointer Technique:
1. Initialize Pointers: Set one pointer at the start (left) and the other at the end (right) of the string. 2. Iterate: Move the pointers toward each other while performing checks: - Ignore non-alphanumeric characters. - Compare the characters at both pointers. If they do not match, the string is not a palindrome. 3. Return Result: If the pointers cross each other without mismatches, the string is a palindrome.
Python Implementation:
Below is a Python function that implements the above logic to check if a string is a valid palindrome.
def is_palindrome(s: str) -> bool:
    # Initialize left and right pointers
    left, right = 0, len(s) - 1

    while left < right:
        # Move the left pointer forward if the character is not alphanumeric
        while left < right and not s[left].isalnum():
            left += 1
        # Move the right pointer backward if the character is not alphanumeric
        while left < right and not s[right].isalnum():
            right -= 1
            
        # Compare characters at both pointers, normalized to lowercase
        if s[left].lower() != s[right].lower():
            return False
        
        # Move both pointers closer
        left += 1
        right -= 1

    return True

# Example usage
input_string = "A man, a plan, a canal: Panama"
print(is_palindrome(input_string))  # Output: True
Explanation of the Code:
1. Pointer Initialization: Two pointers left and right are initialized to the start and end of the string, respectively. 2. Character Checks: - The inner while loops skip over non-alphanumeric characters, ensuring that they do not interfere with palindromic checks. - Characters at the left and right pointers are compared after converting them to lowercase. This allows for case-insensitive comparison. 3. Pointer Movement: After each successful comparison, both pointers are moved closer to the center. 4. Return Value: The function returns True if the string is a palindrome and False otherwise.
Conclusion
Utilizing the two-pointer technique for palindrome validation is both efficient and straightforward. This method ensures that the solution runs in linear time, O(n), with constant space complexity, making it an excellent choice for this type of problem. The provided implementation can be easily adjusted for various input formats by modifying the character normalization rules as needed.