DocsHub
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 matched

The two-pointer approach is efficient — it stops immediately when it finds a mismatch, without checking the rest.

Stepleftrights[left]s[right]Match?
106RR
215AA
324CC
433left >= rightstop

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

TimeSpace
Two pointersO(n)O(1)
Reverse and compareO(n)O(n)

On this page