Two Pointers Pointers from both ends

152. Valid Palindrome

Easy 147 DSA Sheet

You are given a string s. Look only at its letters and digits, and return true if they read the same from left to right as from right to left. Return false otherwise.

Every other character is skipped: spaces, punctuation marks and symbols. An uppercase letter and its lowercase form count as the same character. Digits count just like letters, so "1a1" reads the same both ways and "1a2" does not.

If s holds no letters or digits at all, nothing is left to compare, and the answer is true.

Example 1

Input: s = "Top spot: 12-21, top spot!"

Output: true

Explanation: The letters and digits, all in lowercase, are topspot1221topspot. That string reads the same from both ends.

Example 2

Input: s = "Was it a rat I saw? 9"

Output: false

Explanation: Without the 9, the letters wasitaratisaw read the same both ways. But the 9 counts too, and the string starts with a w, not a 9.

Example 3

Input: s = " :-) "

Output: true

Explanation: The string holds two spaces and three punctuation marks, but no letter or digit. Nothing is left to compare, so the answer is true.

Check your understanding

Work out the answer for this input before you write any code.

s = "Top 10 pot"

Constraints

  • 1 ≤ s.length ≤ 2 × 105
  • s holds printable ASCII characters only (codes 32 to 126): letters, digits, spaces and punctuation.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.