Skip to content

Two Pointers

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

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: