Pattern 2 — Two Pointers
Sometimes you don't need two loops — you need two fingers. This pattern is exactly that, and it's one of the tidiest tricks you'll learn.
The idea, in one line
Put one marker at each end of a list and walk them toward each other, doing one pass instead of a loop inside a loop. That's the two pointers pattern.
How to spot it
The big signal is a sorted list, or a string you compare from the front and the back at the same time. The task usually asks for one of these:
- a pair that adds up to a target — like two response times that fit an SLA budget
- a palindrome check — reads the same forwards and backwards
- reversing a list in place — no copy, no slicing
The move, step by step
- Put left at the first index and right at the last.
- Add the two values and compare to the target.
- Total too small? Move left up one to gain value.
- Total too big? Move right down one to lose value.
- Equal? You found your pair. Keep going while left is below right.
See it work
# Two response times that add up to a target budget (sorted input)
def has_pair(nums, target):
left, right = 0, len(nums) - 1
while left < right:
total = nums[left] + nums[right]
if total == target:
return (nums[left], nums[right])
if total < target:
left += 1 # need more -> move left up
else:
right -= 1 # too much -> move right down
return None
print(has_pair([1, 2, 4, 5, 9], 9)) # (4, 5)Read it top to bottom: start at both ends, nudge whichever end you need, and stop the moment the two markers meet. A palindrome check is the very same shape — compare the two ends, step inward, and fail the instant they differ.
# Palindrome check: compare the ends, step inward
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left, right = left + 1, right - 1
return True
print(is_palindrome("abccba")) # TrueAdvanced — why it's fast, and why sorting matters
Because the list is sorted, it has a direction: moving a pointer doesn't just skip one item, it rules out a whole range you'll never need to check again. That's what turns a slow double loop into a single pass.
Grounded in the GeeksforGeeks 'Two Pointers Technique' tutorial