Valid Palindrome

Easy#125towards each other

You get a string. Find out whether it reads the same left to right and right to left once you keep only the letters and digits and ignore upper and lower case. Our example: "Taco, cat!" — yes, it is a palindrome.

125 Valid PalindromeWalkthrough · 1×

Example: "Taco, cat!". The pointers walk in from both ends and step over anything that is not a letter or a digit.

0T1a2c3o4,5␣6c7a8t9!left
not checked yetunder a pointermatchedskipped

left starts at the first character, "T"

01/34
restart · back · play · step
Speed
1function isPalindrome(s):
2 left = 0
3 right = len(s) - 1
4 while left < right:
5 if not isLetterOrDigit(s[left]):
6 left = left + 1
7 else if not isLetterOrDigit(s[right]):
8 right = right - 1
9 else if lower(s[left]) != lower(s[right]):
10 return false
11 else:
12 left = left + 1; right = right - 1
13 return true
state
left
0
right
–
s[left]
T
s[right]
–
historyclick a step to go back

← → step · space play/pause

Why it works

  1. A palindrome means the first character equals the last, the second equals the one before last, and so on. So compare from both ends.
  2. Punctuation and spaces take no part in the comparison: a pointer simply steps over them.
  3. The first pair that differs means "no". Once the pointers meet, every pair has matched: "yes".

Complexity

Time O(n): each pointer crosses the string at most once. Memory O(1): no cleaned-up copy of the string is made.

nextNow solve it yourself, no hints.

Solve it here →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.