Skip to the workspace
Pebellslearn by building
Two Pointers  ›  Lesson

Converging Pointers: Checking From Both Ends

Valid Palindrome 12 minTwo indexes that start at the two ends of a sequence and step toward each other can compare it with its own reverse in one pass and without copying it.

leetcode / Converging Pointers: Checking From Both Ends

Explore each scene at your own pace.

01 · The rule

The rule

Converging Pointers: Checking From Both Ends

A sign-maker wants to know whether a slogan reads the same forwards and backwards once spaces, punctuation and capital letters are ignored. "Top, spot!" does. The obvious fix is to clean the text, reverse it and compare, which builds two new strings. Two fingers, one at each end of the original text, can do the same check without copying anything.

The rule

Start at both ends, compare, and walk inward until they meet.

Put left on the first character and right on the last. At each step, either skip a character that does not count, or compare the two characters that do. A mismatch ends the check at once; a match moves both pointers one step inward.

def reads_same_both_ways(text):
    left, right = 0, len(text) - 1
    while left < right:
        if not text[left].isalnum():
            left += 1                            # skip punctuation or a space
        elif not text[right].isalnum():
            right -= 1
        elif text[left].lower() != text[right].lower():
            return False                         # a real mismatch
        else:
            left += 1                            # a match: both step inward
            right -= 1
    return True

Every step moves at least one pointer, and they never cross, so the loop runs at most n times. Nothing is copied, so the extra memory is constant: two integers. When the pointers meet, every pair has matched, and a single leftover middle character has nothing to be compared with.

This is the first of two pointer shapes. Converging pointers start at the two ends and move toward each other, as here. Same-direction pointers both start at the left, with one running ahead of the other; you will meet that shape again inside sliding windows.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.