InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Valid Palindrome

easy Original ↗ 00:00

Problem

Given a string s, first convert all uppercase letters to lowercase and remove every character that is not a letter or a digit. Return True if the result reads the same forwards and backwards, and False otherwise.

An empty result (for example, a string of only punctuation and spaces) counts as a palindrome.

Examples

  • s = "A man, a plan, a canal: Panama"True After cleaning: "amanaplanacanalpanama", which reads the same both ways.
  • s = "race a car"False Cleaned: "raceacar" — reversed it is "racaecar", not equal.
  • s = " "True Cleaning removes everything; the empty string is a palindrome by definition.
  • s = "0P"False Digits count: cleaned is "0p", and "0" != "p".

Constraints

  • 1 <= s.length <= 2 * 10^5
  • s consists of printable ASCII characters.
  • Expected O(n) time; the follow-up asks for O(1) extra space (no cleaned copy).

Think about it first

Hint 1 The two-step statement (clean, then compare with the reverse) can be coded literally. Python provides `str.isalnum()` to keep only letters and digits, and slicing `[::-1]` to reverse.
Hint 2 To avoid building the cleaned copy, compare the string against itself with one pointer from the front and one from the back. When a pointer lands on a non-alphanumeric character, skip it.
Hint 3 Advance `left` past non-alphanumerics, retreat `right` past non-alphanumerics, then compare `s[left].lower()` with `s[right].lower()`. Any mismatch returns `False`; if the pointers cross without a mismatch, return `True`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug