The two pointers technique uses two indexes that move through the same structure, usually one from each end, to avoid a double loop. It turns O(n²) problems into O(n).
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("level")) # True
print(is_palindrome("python")) # False
def pair_with_sum(sorted_list, target): # SORTED list
left, right = 0, len(sorted_list) - 1
while left < right:
s = sorted_list[left] + sorted_list[right]
if s == target:
return sorted_list[left], sorted_list[right]
if s < target:
left += 1 # we need more: move the left pointer forward
else:
right -= 1 # we overshot: move the right pointer back
return None
print(pair_with_sum([1, 3, 4, 6, 8, 11], 10)) # (4, 6)
- For the pair with a given sum the list must be sorted; if not, sort it first (O(n log n)).
- In the container with most water the pointer on the lower wall is moved: moving the other can never improve the area.
- Another variant uses a “slow” and a “fast” pointer in the same direction (for example, to remove duplicates from a sorted list).
You saw the idea earlier in Classic algorithms with the exercise “Pair with a given sum”; here you apply it to strings and areas in Palindrome ignoring symbols and Container with most water.