Valid Palindrome
Strings: lesson 2 of 11
Two pointers walk inward and settle it in one pass.
Lesson 2 of 11 · 4 min
Valid Palindrome
Step 1 of 7
A palindrome reads the same both ways, so read it from both ends at once — no reversed copy needed.
The Idea
A palindrome reads the same from both ends, so check it from both ends. Put one pointer at the start, one at the end, and walk them toward each other.
One mismatch is a definite no. Meeting in the middle is a definite yes — no reversed copy, no extra memory.
Real-World Example
Barcode and account-number checkers run the same shape of test: read from the front and the back at once and bail the instant the two disagree. Scanning the whole code first, then comparing, wastes the half of the work you already knew was doomed.
The Code
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
if not s[left].isalnum(): # skip junk from the left
left += 1
elif not s[right].isalnum(): # ...and from the right
right -= 1
elif s[left].lower() != s[right].lower():
return False # one mismatch is enough
else:
left, right = left + 1, right - 1
return True
print(is_palindrome("RaceCar!")) # True
print(is_palindrome("byte")) # FalseYour turn
Fill in the blank.
def is_palindrome(s):
left, right = 0, len(s) - 1
while ___:
if s[left] != s[right]:
return False
left, right = left + 1, right - 1
return True
print(is_palindrome("abba"), is_palindrome("abca")) # want True FalseMini quiz
1 / 3