Valid Palindrome

EasyTwo pointers

A phrase counts as a palindrome if, after you lowercase every letter and remove everything that is not a letter or a digit, it reads the same forwards and backwards.

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

Examples

Example 1
Input:  s = "Was it a car or a cat I saw?"
Output: true

Cleaned up, it is wasitacaroracatisaw, the same both ways.

Example 2
Input:  s = "race a cat"
Output: false

raceacat backwards is tacaecar.

Constraints

  • 1 ≤ s.length ≤ 2 × 10⁵
  • s is printable ASCII: letters, digits, spaces and punctuation.

Stuck?

Hint 1

You do not need to build the cleaned-up string. Start one pointer at each end.

Hint 2

Skip anything that is not a letter or a digit, compare the two characters in lowercase, and move both pointers inward.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur