Valid Palindrome
Step 1 of 7
checks0extra memoryO(1)
s
left
right
R
a
c
e
C
a
r
!
01234567
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
Your 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