LeetCode #125 Easy

Valid Palindrome

Valid Palindrome is LeetCode 125 (Easy). Given a string s of printable ASCII characters, return true if it reads the same forwards and backwards once you:

  • remove all non-alphanumeric characters, keeping only letters and digits, and
  • treat uppercase and lowercase letters as the same.

A string with no letters or digits at all counts as a palindrome. s can be 200,000 characters long, so one linear pass is the target.

Constraints
  • 1 <= s.length <= 2 * 10⁵
  • s consists only of printable ASCII characters.
stringtwo-pointers
Open on LeetCode ↗
02

Intuition

In a palindrome the first character matches the last, the second matches the second-to-last, and so on inward. So check it from the outside in: one pointer at each end, moving toward each other, comparing as they go.

  • Characters that do not count: when a pointer sits on a space or punctuation mark, move that pointer alone past it. The two sides can hold different amounts of punctuation, so the pointers do not move in step.
  • Characters that count: compare them in lowercase. One mismatch proves the string is not a palindrome.

If the pointers meet with no mismatch, every pair matched. This check builds no cleaned copy, so it needs only O(1) extra space.

How to spot this pattern

"Does it read the same from both ends" is a two-pointer walk inward. Extra rules about which characters count become a skip step for each pointer, not a preprocessing pass.

03

Approach

Try it first

Before reading on, decide what each pointer should do when it lands on a comma, and how you stop a pointer from running past the other while it skips. Aim for O(n) time and O(1) extra space.

1

Place a pointer at each end

Set left = 0 and right = len(s) - 1. Every character outside the two pointers has already been dealt with, so the loop only runs while left < right.

2

Skip one character that does not count

If s[left] is not a letter or digit, move left one step right and go round again; otherwise, if s[right] is not, move right one step left. Moving one pointer per round means left < right is checked again before the next comparison, so a pointer can never skip past the other.

3

Compare the two characters in lowercase

When both pointers sit on letters or digits, compare s[left].lower() with s[right].lower(). If they differ, return false at once: in any palindrome these two positions must hold the same character.

4

Step both pointers inward

On a match, move both pointers one step in. When they meet or cross, every pair has matched and the answer is true. The middle character of an odd-length string mirrors itself, so it is never compared.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isPalindrome(self, s):
▶3 left, right = 0, len(s) - 1
▶4 while left < right:
▶5 if not s[left].isalnum():
▶6 left += 1
▶7 elif not s[right].isalnum():
▶8 right -= 1
▶9 elif s[left].lower() != s[right].lower():
▶10 return False
▶11 else:
▶12 left += 1
▶13 right -= 1
▶14 return True
R0a1c2e3,4␣5c6a7r8!9leftrightpairs compared, in lowercasenone yetleft at 0, right at 9
left0
right9
One pointer starts at each end of the 10 characters. Only letters and digits take part, and case does not matter. Everything outside the two pointers will already be checked, so the walk only looks between them.
R0a1c2e3,4␣5c6a7r8!9leftrightpairs compared, in lowercasenone yet'!' does not count → right moves on
left0
right8
Left is on 'R', which counts. The right pointer was on '!', which does not, so only the right pointer moves one step left.
R0a1c2e3,4␣5c6a7r8!9leftrightpairs compared, in lowercaser0=r8'r' matches 'r' → both step in
left0
right8
'R' at 0 and 'r' at 8 both count, and they are equal once lowercased. This pair mirrors correctly, so both pointers move one step inward.
R0a1c2e3,4␣5c6a7r8!9leftrightpairs compared, in lowercaser0=r8a1=a7'a' matches 'a' → both step in
left1
right7
'a' at 1 and 'a' at 7 both count and are equal. This pair mirrors correctly, so both pointers move one step inward.
R0a1c2e3,4␣5c6a7r8!9leftrightpairs compared, in lowercaser0=r8a1=a7c2=c6'c' matches 'c' → both step in
left2
right6
'c' at 2 and 'c' at 6 both count and are equal. This pair mirrors correctly, so both pointers move one step inward.
R0a1c2e3,4␣5c6a7r8!9leftrightpairs compared, in lowercaser0=r8a1=a7c2=c6the space does not count → right moves on
left3
right4
Left is on 'e', which counts. The right pointer was on the space, which does not, so only the right pointer moves one step left.
R0a1c2e3,4␣5c6a7r8!9bothpairs compared, in lowercaser0=r8a1=a7c2=c6',' does not count → right moves on
left3
right3
Left is on 'e', which counts. The right pointer was on ',', which does not, so only the right pointer moves one step left.
R0a1c2e3,4␣5c6a7r8!9pairs compared, in lowercaser0=r8a1=a7c2=c6pointers meet → palindrome
resulttrue
Every pair matched, and the middle character 'e' mirrors itself. The pointers have nothing left between them, so the string is a valid palindrome: return true.
05

Clean the string, then reverse it

Build a new string from the letters and digits only, in lowercase. The original is a valid palindrome exactly when that cleaned string equals its own reverse.

▶1class Solution:
▶2 def isPalindrome(self, s):
▶3 cleaned = [c.lower() for c in s if c.isalnum()]
▶4 return cleaned == cleaned[::-1]
06

Common pitfalls

Skipping in an inner loop with no bounds check

✗ Wrong
while not s[left].isalnum():
    left += 1
✓ Right
while left < right and not s[left].isalnum():
    left += 1

On ".," the inner loop moves left past both characters and then reads s[2], which does not exist, so the code crashes. Any string made only of punctuation and spaces triggers it, and the right answer for such a string is true.

Keeping letters but dropping digits

✗ Wrong
if not s[left].isalpha():
✓ Right
if not s[left].isalnum():

Digits count too. On "0P" the wrong check skips the 0, leaves only P, and returns true. The real comparison is 0 against p, so the answer is false.

Comparing before lowercasing

✗ Wrong
elif s[left] != s[right]:
✓ Right
elif s[left].lower() != s[right].lower():

Case is ignored, so "Aa" must return true. The raw comparison sees A and a as different characters and returns false.

07

Edge cases

No letters or digits at all

For " " or "?!", the pointers skip until they meet without making a single comparison, and the answer is true: the empty string reads the same both ways.

A single character

left and right start equal, the loop never runs, and the answer is true.

08

Complexity

Time
O(n)
Space
O(1)
Each round of the loop moves at least one pointer one step inward, and the pointers start n − 1 apart, so there are fewer than n rounds. Only the two indices are stored.
09

Valid Palindrome FAQ

Does Python's isalnum match the problem's idea of alphanumeric?

For this problem, yes, because the input is printable ASCII. On other text, str.isalnum() also accepts letters such as é and symbols such as ², and Java's Character.isLetterOrDigit accepts é too. If the input could hold non-ASCII text, test the ranges a-z, A-Z and 0-9 directly.