Easy

Valid Palindrome

Description

Ignore non-alphanumeric ASCII characters and letter case; decide whether the remaining string reads identically in both directions.

Solution

def is_palindrome(s):
    left, right = 0, len(s)-1
    while left < right:
        if not s[left].isalnum():
            left += 1
        elif not s[right].isalnum():
            right -= 1
        elif s[left].lower() != s[right].lower():
            return False
        else:
            left += 1
            right -= 1
    return True

Examples

Inputs are positional arguments. Trees use level-order arrays; linked lists use value arrays. Design problems list operations in order.

Example 1

Input
["A, b! a"]
Output
true

Ignoring punctuation and case leaves aba.

Example 2

Input
["ab"]
Output
false

The endpoints differ.

Example 3

Input
["! "]
Output
true

Ignoring punctuation leaves an empty palindrome.

Approach

Move two pointers inward, skipping ignored characters and comparing normalized letters.

Time & space

O(n) time; O(1) auxiliary space. Here n is the input length.