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 TrueEvery 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.