KatInterview

Mirror Check Ignoring Punctuation and Letter Case

StringsAuto-graded · 24 test cases
EasyAuto-gradedStringstwo-pointersstringspalindrome

Last updated

Check whether a string is a palindrome when only letters and digits count and case is ignored, using two pointers with constant extra space.

You are given a string text. Consider only its alphanumeric characters (letters and digits), and treat uppercase and lowercase versions of a letter as the same character. Every other character (spaces, punctuation, symbols, underscores) is ignored.

Return True if the remaining characters, read in order, are identical to the same characters read in reverse. Otherwise return False.

Details:

  • If no alphanumeric characters remain (for example, an empty string or a string of only spaces and punctuation), the answer is True.
  • Digits count as real characters and must match like any other character.
  • Aim for O(n) time and O(1) extra space. Do not build a filtered or reversed copy of the string; compare characters in place by moving two indices toward each other.

Constraints

  • 0 <= len(text) <= 2 * 10^5
  • text consists of printable ASCII characters.
  • Return a boolean.

Examples

Example 1

Input: is_mirror_text('A man, a plan, a canal: Panama')

Output: True

Example 2

Input: is_mirror_text('race a car')

Output: False

Example 3

Input: is_mirror_text(' ')

Output: True

Example 4

Input: is_mirror_text('No \'x\' in Nixon')

Output: True

Hints

Hint 1

Building a cleaned copy and comparing it to its reverse works, but it uses O(n) extra memory. Try to check the original string directly.

Hint 2

Place one index at the start and one at the end. Move each one inward until it points at an alphanumeric character, then compare the two characters ignoring case.

Hint 3

Keep the `left < right` condition in the skipping loops so the indices never cross or leave the string when a side contains only punctuation. Remember that digits are significant.