Two pointers · Easy

Valid palindrome

Ignore non-alphanumeric characters and case. Return whether the string is a palindrome. Compare the letters and digits from the outside in, treating uppercase and lowercase as equal.

Worked example

'A man, a plan, a canal: Panama' → True

  1. Ignoring spaces, punctuation, and case gives amanaplanacanalpanama.
  2. Compare the outer a values, then the m values, and continue toward the middle. Every pair matches.

Python solution

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

Skip punctuation at both ends and compare inward.

Time: O(n) · Space: O(1)

Practise in GymType