📖 6 min read
Last updated on

Valid Palindrome — Coding Interview Walkthrough


You’re five minutes into a phone screen. The interviewer pulls up Valid Palindrome — a classic warm-up that looks trivial until you realize they’re watching how you handle the details, not whether you can reverse a string. The candidates who stumble here aren’t missing the algorithm; they’re missing the constraint about alphanumeric characters or forgetting to lowercase before comparing.


The Problem

A phrase is a palindrome if, after converting all uppercase letters to lowercase and removing all non-alphanumeric characters, it reads the same forward and backward.

Given a string s, return true if it is a palindrome, or false otherwise.

Example

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

Output true

After cleaning: "amanaplanacanalpanama" reads the same forwards and backwards.

Input s = "race a car"

Output false

After cleaning: "raceacar" does not read the same in reverse.

Already comfortable with the solution? Practice it in a mock interview →


What Interviewers Are Actually Testing

This problem is rarely about the algorithm itself. It’s about how you handle the details.

SkillWhat Interviewers Observe
Requirement parsingDo you notice the “alphanumeric only, case-insensitive” constraint immediately?
Edge case awarenessDo you handle empty strings, single characters, and all-punctuation inputs?
Space optimizationDo you know the difference between an extra-space and in-place two-pointer approach?
Code clarityAre your variable names and logic readable without explanation?
CommunicationDo you talk through your reasoning before diving into code?

Step 1 — Clarifying Questions

Before writing a single line of code, ask these questions:

  1. What counts as alphanumeric? Letters (a–z, A–Z) and digits (0–9). Confirm this matches the problem constraints, since some variants include spaces.

  2. Is the comparison case-sensitive? No. The problem says to normalize to lowercase first. Good to state this explicitly so the interviewer knows you read it.

  3. What should we return for an empty string or a string that’s all punctuation? Confirm it should return true (empty string is a palindrome by convention).

  4. Are we allowed to use extra space, or does it need to be in-place? This opens the door to discussing the O(n) space approach (clean then reverse) versus the O(1) space two-pointer approach.


Step 2 — A First (Non-Optimal) Idea

The most natural first instinct: clean the string, then check if it equals its reverse.

def isPalindrome(s: str) -> bool:
    cleaned = [c.lower() for c in s if c.isalnum()]
    return cleaned == cleaned[::-1]

This works and is actually acceptable in most interviews. It’s clean, readable, and correct. The complexity is:

  • Time: O(n) — one pass to filter, one pass to reverse, one pass to compare
  • Space: O(n) — we create a new list of up to n characters

The downside: we allocate extra memory proportional to the input size. If the interviewer asks you to optimize for space, you need the two-pointer approach.


Step 3 — The Key Insight

You don’t need to build a cleaned copy of the string at all.

Instead, use two pointers — one starting at the left, one at the right — and skip non-alphanumeric characters as you go. Compare only the alphanumeric characters directly, in place.

The key realization: a palindrome check only needs to compare the character at position i with its mirror at position n-1-i. You can do this without ever materializing the cleaned string.

This brings space down from O(n) to O(1).

Cleaned string with L pointer at left, R pointer at right. Two pointers move inward comparing characters until they meet. ---

Step 4 — Optimal Strategy

  1. Initialize a left pointer at index 0 and a right pointer at len(s) - 1.
  2. While left < right:
    • Advance left forward while it points to a non-alphanumeric character.
    • Advance right backward while it points to a non-alphanumeric character.
    • If left >= right, break — we’ve crossed the midpoint.
    • Compare s[left].lower() and s[right].lower().
    • If they differ, return False.
    • Otherwise, move both pointers inward (left += 1, right -= 1).
  3. If the loop completes without a mismatch, return True.

Python Implementation

def isPalindrome(s: str) -> bool:
    left, right = 0, len(s) - 1

    while left < right:
        # Skip non-alphanumeric characters from the left
        while left < right and not s[left].isalnum():
            left += 1

        # Skip non-alphanumeric characters from the right
        while left < right and not s[right].isalnum():
            right -= 1

        # Compare the characters at both pointers (case-insensitive)
        if s[left].lower() != s[right].lower():
            return False

        left += 1
        right -= 1

    return True

The guard left < right in both inner while loops prevents the pointers from crossing while skipping characters — an easy-to-miss edge case.


Time & Space Complexity

OperationComplexity
Scanning the string with two pointersO(n)
.isalnum() and .lower() per characterO(1)
Overall timeO(n)
Overall spaceO(1)

Each character is visited at most once by either pointer. No extra data structures are created.


Common Interview Mistakes

  1. Forgetting the left < right guard inside the inner while loops. Without it, the pointers can cross when all remaining characters are non-alphanumeric, causing incorrect comparisons.

  2. Not lowercasing before comparing. 'A' != 'a' in Python. Easy to forget under pressure.

  3. Using s.isalpha() instead of s.isalnum(). isalpha() excludes digits. The problem explicitly includes digits as valid alphanumeric characters.

  4. Treating the cleaned-string approach as wrong. It’s O(n) space but perfectly valid. Don’t apologize for it. Present it, state the tradeoff, then offer to optimize if asked.

  5. Starting to code before clarifying the empty-string case. Interviewers notice when candidates code first and discover edge cases last.

  6. Off-by-one errors in the pointer movement. Forgetting left += 1 and right -= 1 at the end of the loop body causes an infinite loop.


What a Strong Candidate Sounds Like

“So after reading the problem, the key constraints are: ignore non-alphanumeric characters and treat it as case-insensitive. The simple approach is to filter the string, then check if it equals its reverse — that’s O(n) time and O(n) space. I’ll start there so we have something correct, then I can optimize for space using two pointers if that’s useful. The two-pointer version avoids creating the cleaned string entirely — we just skip non-alphanumeric characters as we scan inward, and compare only what’s relevant. The tricky part is making sure the inner skip loops still respect the left < right boundary.”


Example Interview Dialogue

Interviewer: Walk me through your approach.

Candidate: I’ll use two pointers — one from each end. At each step I skip non-alphanumeric characters, then compare the two characters case-insensitively. If they ever differ, it’s not a palindrome. If the pointers meet in the middle without a mismatch, it is.

Interviewer: What happens if the string is something like "!@#"?

Candidate: Good edge case. After skipping all the non-alphanumeric characters, both pointers will converge without ever comparing anything — the loop exits and we return true. An empty or all-punctuation string is trivially a palindrome. I handle this implicitly because the inner while loops stop when left >= right.

Interviewer: Can you make it more space efficient?

Candidate: The two-pointer approach is already O(1) space — we’re working directly on the original string with just two integer indices. No extra arrays or cleaned strings.


  1. Valid Palindrome II — Same idea, but you’re allowed to remove at most one character. Forces you to handle a branch when pointers mismatch.

  2. Longest Palindromic Substring — Expand-around-center technique, shares the two-pointer intuition.

  3. Palindrome Linked List — Palindrome check on a linked list, combining two-pointer with reversal.


Practice This in a Mock Interview

Reading about Valid Palindrome is very different from solving it in real time while an interviewer watches. The mistakes candidates make — forgetting .isalnum(), missing the inner guard, not explaining before coding — almost never show up when reading a solution. They show up under pressure.

Start a mock interview for Valid Palindrome on Intervu.


Further reading:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →