Skip to content
mlmentorship

Valid Palindrome

Repair one irrelevant endpoint at a time, preserve matched outer pairs, and distinguish per-character lowercase from normalization and one-deletion edits.

Published · 14 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

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

ML breadth · closed-book attempt

Valid Palindrome

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

Problem

Input. A Python string text. Output. Return True if its retained characters match in forward and reverse order; otherwise return False. Rules. Retain characters accepted by Python isalnum() and compare each retained code point's lower() result. Punctuation and whitespace are ignored. This is not whole-string case folding, normalization, or grapheme comparison. Leave the string unchanged. Empty and entirely filtered strings return True. Example. "A man, a plan, a canal: Panama" returns True. For "race a car", return False; for "!!!", return True.

08:00recommended time

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

30-second answer map

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

Problem trace

Skip punctuation before comparing the two remaining characters

Worked example: skip non-alphanumeric characters before comparing the endsFor A,b:a, normalization gives aba. The punctuation never participates in an equality comparison; the retained letters match from both ends.Skip punctuation, normalize case,then compare the retained endsA,b:aabaRetained lowercase sequence: abaCompare the two a ends; punctuationnever enters the comparison.
Read it this way: For A,b:a, normalization gives aba. The punctuation never participates in an equality comparison; the retained letters match from both ends. Would comparing raw uppercase A against lowercase a without normalization preserve this answer?
Full interview answer 14 min read

Check whether a string reads the same both ways after ignoring nonalphanumeric characters and letter case.

Problem

Input. A Python string text.

Output. Return True if its retained characters match in forward and reverse order; otherwise return False.

Rules. Retain characters accepted by Python isalnum() and compare each retained code point’s lower() result. Punctuation and whitespace are ignored. This is not whole-string case folding, normalization, or grapheme comparison. Leave the string unchanged. Empty and entirely filtered strings return True.

Example. "A man, a plan, a canal: Panama" returns True. For "race a car", return False; for "!!!", return True.

Picture

Keep raw "A, b a!" at indices zero through six. left and right bound the unanswered interval.

ActionRemaining raw indices
Initialize[0,6]
Skip right ! only[0,5]
Match A.lower() with a.lower()[1,4]
Skip left comma[2,4]
Skip left space[3,4]
Skip right space[3,3]

Only the center b remains. It equals itself, so the answer is True.

Outside [left,right], every retained pair matches and every discarded character is irrelevant. Skipping punctuation preserves that claim. Matching both endpoints certifies a pair before moving both pointers.

A relevant mismatch proves False: neither endpoint may be discarded under this policy.

One irrelevant endpoint permits only one pointer move. Advancing both after skipping ! in "!ab" would miss the unequal a,b pair.

Problem trace

Separate raw string: repair one irrelevant endpoint, then compare normalized ends

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
L
0
R
6
covered range
[0..6]

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.
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.
Check: Why does encountering ! move only R? Why is no comparison needed once both pointers reach b?
Reference drawing

Problem trace

Skip punctuation before comparing the two remaining characters

Worked example: skip non-alphanumeric characters before comparing the endsFor A,b:a, normalization gives aba. The punctuation never participates in an equality comparison; the retained letters match from both ends.Skip punctuation, normalize case,then compare the retained endsA,b:aabaRetained lowercase sequence: abaCompare the two a ends; punctuationnever enters the comparison.
Execution trace
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
L
0
R
6
covered range
[0..6]

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.
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.
Check: Why does encountering ! move only R? Why is no comparison needed once both pointers reach b?
Read it this way: For A,b:a, normalization gives aba. The punctuation never participates in an equality comparison; the retained letters match from both ends. Would comparing raw uppercase A against lowercase a without normalization preserve this answer?

Code

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

Each pointer moves monotonically, so raw code points require bounded-character work and auxiliary space.

isalnum() includes non-ASCII letters and numbers. It is not an ASCII-only test.

Change the Comparison Contract

Start from valid_palindrome. Two adjustable parts are normalization and permission to delete a relevant character.

  1. Normalize before comparing.

    New task: Apply Unicode NFKC compatibility normalization, then case folding, then alphanumeric filtering.

    Picture and change: A raw character can expand into several normalized characters. Replace raw pointers with a transformed sequence.

    Code: Complete replacement with an explicit normalization policy:

    import unicodedata
    
    
    def unicode_normalized_palindrome(text):
       normalized = unicodedata.normalize("NFKC", text).casefold()
       comparable = [char for char in normalized if char.isalnum()]
       return comparable == comparable[::-1]

    Check: "\u00dfs" folds to sss, so it returns True; the reference returns False. Fullwidth "\uff21b\uff41" normalizes to aba.

    NFKC and case folding are declared choices, not universal language rules. Grapheme handling remains unspecified. Normalization adds work. For transformed length , the comparison and stored sequences cost time and space.

    Use when: The product requires this exact equality policy, including its compatibility transformations.

  2. Permit one deletion.

    New task: Check already comparable ASCII text after deleting at most one character.

    Picture and change: At the first mismatch, one unequal endpoint must go. Test both remaining intervals without further deletions.

    Code: Complete replacement. This version does not filter punctuation or change case.

    def palindrome_one_deletion(text):
       def matches(left, right):
          while left < right:
             if text[left] != text[right]:
                return False
             left, right = left + 1, right - 1
          return True
    
       left, right = 0, len(text) - 1
       while left < right:
          if text[left] != text[right]:
             return matches(left + 1, right) or matches(left, right - 1)
          left, right = left + 1, right - 1
       return True

    Check: abca returns True by deleting b or c; abc returns False.

    Greedily deleting left fails on abbab: only deleting the right endpoint at its first mismatch succeeds. At most two extra interval scans preserve time and auxiliary space.

    Use when: A relevant mismatch may be repaired, not merely rejected.

Rebuild the Boundary

Why can an odd center remain unpaired? Does this algorithm find the longest palindromic substring?

Answer: The center equals itself; outer relevant pairs are already verified. This checks the complete sequence, not candidate substrings.