A pointer is simply a position. With two pointers, we can watch two places in a sequence and move them according to what we learn.
Start at opposite ends
To check whether a word reads the same forward and backward, compare its first and last letters. If they match, move both pointers inward.
- Opposite ends help with palindromes and sorted pairs.
- Two forward pointers can compare or merge sorted lists.
- A slow and fast pointer can track different kinds of progress.
Each move removes possibilities
The power comes from knowing which direction is safe. In a sorted list, a sum that is too small tells us to move the left pointer right.
def is_palindrome(word):
left = 0
right = len(word) - 1
while left < right:
if word[left] != word[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome("level")) # TrueBoth pointers cross the sequence only once, so the work is O(n). No reversed copy is required.
Your tiny challenge
Use two pointers to compare the first and last numbers of a list, then the second and second-to-last. When should the loop stop?
