Two-Pointer Technique · Data Structures & Algorithms
Ch 2 · Arrays & Lists — The Workhorse — card 3 of 3.
Many array problems become O(n) instead of O(n²) with two pointers — one starting at the left, one at the right, walking toward each other. Here we check if a word is a palindrome without building anything new.
def is_palindrome(text):
left, right = 0, len(text) - 1
while left < right:
if text[left] != text[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False