Python coding

Palindrome ignoring punctuation

Given a string s, return True if it reads the same forwards and backwards when you look only at its letters and digits and ignore case; otherwise return False. Spaces and punctuation are skipped. A string with no letters or digits counts as a palindrome.

s contains only ASCII characters. Aim for O(1) extra space: do not build a cleaned copy.

  • is_palindrome("Was it a car or a cat I saw?") → true
  • is_palindrome("Not a palindrome") → false
  • is_palindrome("No lemon, no melon") → true
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Put one index at each end and move them toward each other, comparing the characters they point at.

Hint 2

If either index sits on a character that is not a letter or a digit, move only that index and compare nothing. Compare in lowercase.

Hint 3

Every skip must still respect lo < hi, or a string of only punctuation runs past the end. Digits are kept: use isalnum, not isalpha.

Solution and why it works
pythonO(n) · O(1)
def is_palindrome(s: str) -> bool:
    lo, hi = 0, len(s) - 1
    while lo < hi:
        if not s[lo].isalnum():
            lo += 1                      # skip on the left, compare nothing
        elif not s[hi].isalnum():
            hi -= 1                      # skip on the right
        elif s[lo].lower() != s[hi].lower():
            return False
        else:
            lo, hi = lo + 1, hi - 1
    return True

The first kept character must match the last, the second the second-to-last, and so on: two indexes walking inward check exactly those pairs in one pass with no extra memory. Moving a single pointer per iteration keeps one lo < hi guard; nested skip loops without it run off the end on a string like ".,!". Digits count: with isalpha instead of isalnum, "9z" wrongly passes.

Related lab: Loops in motion