Skip to content
BytePatterns

Two Pointers

Arrays: lesson 2 of 14

Two indexes closing in beat one loop nesting another.

Lesson 2 of 14 · 5 min

Two Pointers

Step 1 of 9

The array is sorted, so start as wide as possible: one pointer at each end.

The Idea

Keep one index at each end and move them toward each other based on what you see. Every step rules out a whole group of pairs at once. Brute force checks every pair in O(n²); two pointers does the same job in O(n).

Real-World Example

Two people search a long bookshelf for a matching pair of volumes, one starting at each end and walking inward. They meet in the middle having covered the shelf exactly once, rather than one person re-walking it for every single book.

The Code

def two_sum_sorted(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return (left, right)
        if total < target:
            left += 1        # need a bigger sum
        else:
            right -= 1       # need a smaller sum
    return None

# two_sum_sorted([1, 3, 4, 8, 11], 11) -> (1, 3)

Python

Your turn

What does this print?

nums = [2, 5, 9]
l, r = 0, 2
while l < r:
  print(nums[l] + nums[r])
  l += 1
  r -= 1

Mini quiz

1 / 3

On sorted input, two pointers turn an O(n²) pair search into:

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.