Skip to the solution
EasyDSA6 min read

How do you check if a string is a valid palindrome?

459 views

The problem

Question presented to candidate: "Given a string, tell me whether it is a palindrome if you only look at letters and digits and ignore case. For example, "A man, a plan, a canal: Panama" should be true. Please write it in Python."

What a strong answer should cover:

  • Converging two pointers that skip non-alphanumeric characters and compare case-insensitively; stop at the first mismatch.
  • The inner skip loops also check left < right, so a string of only punctuation does not run out of bounds.
  • O(n) time and O(1) extra space, versus O(n) extra space for the clean-and-reverse one-liner.
  • Edge cases: empty string, only punctuation, single character, digits versus letters ("0P" is false).
  • Python specifics: str.isalnum() and str.lower() are Unicode-aware; s[::-1] builds a full copy; casefold() is the stricter case-insensitive comparison.

Clarifying questions expected:

  • "Only letters and digits, and is it case-insensitive?"
  • "ASCII or full Unicode? And is an empty string a palindrome?"

Code / implementation expected: Yes โ€” is_palindrome(s) with two indices in Python; the one-line cleaned version is a good warm-up to mention.

  • dsa
  • two-pointers
  • strings

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonTwo-pointer palindrome check on tricky inputs
PythonValid palindrome II (one deletion) and the clean-and-reverse version

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 28 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you check if two strings are anagrams?

Continue