Two fingers on a list
Many problems become easy if you keep two positions (pointers) in the list at once, and move them step by step. Usually one starts at the left end and one at the right end.
Think of it like this: Checking if a word reads the same backwards: put one finger on the first letter and one on the last. Compare, then move both fingers inward.
Is it a palindrome?
def is_palindrome(word):
left, right = 0, len(word) - 1
while left < right:
if word[left] != word[right]:
return False
left += 1
right -= 1
return True
print(is_palindrome("racecar"))
print(is_palindrome("python"))Output
True False
Pair with a target sum (sorted list)
Find two numbers in a sorted list that add up to a target. Checking every pair is O(n²). With two pointers it's O(n):
def pair_sum(nums, target):
left, right = 0, len(nums) - 1
while left < right:
s = nums[left] + nums[right]
if s == target:
return nums[left], nums[right]
if s < target:
left += 1 # need a bigger sum: move the small end up
else:
right -= 1 # need a smaller sum: move the big end down
return None
print(pair_sum([1, 3, 4, 6, 8, 11], 10))
print(pair_sum([1, 2, 3], 100))Output
(4, 6) None
Because the list is sorted, moving left right always makes the sum bigger, and moving right left always makes it smaller. So each step safely rules out one number.
Remember: Two pointers works best on sorted lists, or when you compare both ends of something.