Skip to content
mlmentorship

Valid Palindrome

Ignore punctuation and letter case, then check whether text reads the same both ways.

Published · 5 min read ·Core ·Mixed

30-second answer map

Visual first · depth when needed

Keep raw text in place, skip non-alphanumeric endpoints one at a time, and move both pointers only after a case-insensitive match.

Preparing the visual…

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

How practice works

ML breadth · closed-book attempt

Valid Palindrome

Explain the mechanism, why it works, when it fails, and one alternative.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

Ignore punctuation and letter case, then check whether text reads the same both ways.

Start with the concrete trace below. It shows the state the algorithm must carry as it runs.

Problem trace

Valid Palindrome: Keep raw text in place, skip non-alphanumeric endpoints one at a time, and move both pointers only after a case-insensitive match.

Input and goalIgnore punctuation and letter case, then check whether text reads the same both ways.
Initialize at both raw endpointsFor "A, b a!", L=0 points to A and R=6 points to !.
LA0,1space2b3space4a5R!6
coveredRange[0..6]actioninitialize opposite-end pointers

Recognize it
Use opposite-end pointers when equality must hold symmetrically after ignoring characters, case, or other endpoint noise.
Keep true
Before each loop iteration, every accepted alphanumeric pair outside [left,right] matches case-insensitively; discarded outside characters are non-alphanumeric and cannot affect the answer.
Reuse it
When irrelevant data appears at either boundary, repair one endpoint at a time until both are comparable; only then apply the symmetric predicate and advance both.
Read it this way: For "A, b a!", L=0 points to A and R=6 points to !. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.

Pattern: Two pointers at opposite ends.

Simple idea: Skip non-letter and non-number characters. Compare the next real character from each side, then move inward.

def valid_palindrome(text: str) -> bool:
   left, right = 0, len(text) - 1

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

Cost: time and space.