The Mirror Test

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Slalom

Problem

Given a string, return True if it reads the same forwards and backwards when considering only alphanumeric characters and ignoring case. Empty string returns True.

Check if a string reads the same forwards and backwards.

Example 1

Input:

s = "A man, a plan, a canal: Panama"

Output:

true

Example 2

Input:

s = "race a car"

Output:

false

Worked solution and explanation

Why this problem exists in real interviews

This tests two-pointer string comparison with filtering. It goes beyond simple reversal by requiring candidates to skip non-alphanumeric characters and ignore case, testing both pointer management and character classification.


Break down the requirements

Step 1: Set up two pointers at opposite ends

Left pointer starts at 0, right pointer at the last index.

Step 2: Skip non-alphanumeric characters

Advance each pointer past spaces, punctuation, and symbols. Only compare alphanumeric characters.

Step 3: Compare characters case-insensitively

Convert both characters to lowercase before comparing. If they differ, the string is not a palindrome.

Step 4: Handle the empty string

An empty string is defined as a palindrome.


The solution

Two-pointer with alphanumeric filtering
def is_palindrome(s):
    left = 0
    right = len(s) - 1
    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True

Common follow-up questions