Animations
Palindrome Checker — Visual Walkthrough
Watch two pointers walk inward from both ends, comparing characters until they meet in the middle.
Palindrome Checker
Input: "RACECAR"
Two pointers start at opposite ends and walk toward each other. At every step — compare the outer characters. If they always match until the pointers meet — it is a palindrome.
Palindrome Checkertwo pointers · O(n)
inputRACECAR
R
[0]A
[1]C
[2]E
[3]C
[4]A
[5]R
[6]left—
s[left]—
right—
palindrome.py
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
# compare outer characters
if s[left] != s[right]:
return False # mismatch!
left += 1; right -= 1
return True # all pairs matched
Call is_palindrome("RACECAR")
step 0/15
0%
How it works
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False # mismatch — not a palindrome
left += 1
right -= 1
return True # all pairs matchedThe two-pointer approach is efficient — it stops immediately when it finds a mismatch, without checking the rest.
| Step | left | right | s[left] | s[right] | Match? |
|---|---|---|---|---|---|
| 1 | 0 | 6 | R | R | ✓ |
| 2 | 1 | 5 | A | A | ✓ |
| 3 | 2 | 4 | C | C | ✓ |
| 4 | 3 | 3 | left >= right | — | stop |
The two-pointer approach only checks n/2 pairs — half the string. As soon as a mismatch is found, it returns False immediately without checking the rest. This makes it faster than reversing the whole string and comparing.
Complexity
| Time | Space | |
|---|---|---|
| Two pointers | O(n) | O(1) |
| Reverse and compare | O(n) | O(n) |