AlgoViz

Two pointers (pattern)

easy 14 min

Two pointers walks one list with two indexes instead of one.

Video lesson · Chapter 1 of 16

The sorted two-sum challenge

0:00 / 14:30

The two pointer pattern, fully visual

3:26Reel

Two pointers (pattern) in one picture
Two pointers (pattern) in one picture

How it works

Step through the idea, or press Play.

Step 1 of 3

Spot the shape. Sorted input, a pair or window to find, or a list to compact in place

Understand it

Whiteboard sketch: a sorted array 1 3 4 6 8 9 11 14 with a red 'left' arrow on the first cell and a teal 'right' arrow on the last, both moving inward. Note: sum too small, left++; sum too big, right--.
Opposite ends on a sorted list: a small sum moves left up, a big sum moves right down.

The brute-force way to find a pair in a list checks every pair: two nested loops, about n²/2 comparisons. Two pointers gets the same answer in one pass by using structure in the input, usually that it is sorted, to rule out many pairs at once.

Shape 1

Opposite ends

Put left at index 0 and right at the last index. In a sorted list, if nums[left] + nums[right] is too small, no pair that uses nums[left] can work, because every other partner is smaller than nums[right]. So left moves up. If the sum is too big, right moves down for the mirror reason. Stop when they meet.

One step of the scan
  1. 1Check left < rightIf they have met, there is no pair
  2. 2Add the two endsnums[left] + nums[right]
  3. 3Compare with the targetEqual: done. Too small: left += 1. Too big: right -= 1
Repeat: back to Check left < right
Python
left, right = 0, len(nums) - 1while left < right:    total = nums[left] + nums[right]    if total == target:        ...                 # found a pair    elif total < target:        left += 1           # need a bigger sum    else:        right -= 1          # need a smaller sum
The opposite-ends skeleton. Only the comparison changes from problem to problem.

Shape 2

Slow and fast (reader and writer)

Both start at 0. fast visits every item; slow marks where the next kept item goes. When the item under fast should be kept, copy it to slow and advance slow. At the end, the first slow positions hold the answer. The same idea with steps of one and two finds the middle of a linked list or detects a cycle.

Python
slow = 0for fast in range(len(nums)):    if keep(nums[fast]):        nums[slow] = nums[fast]        slow += 1# nums[:slow] is the answer; slow is its length
The reader/writer skeleton. keep(...) is the only problem-specific part.

Why it works

O(n) time, O(1) space

Every loop iteration moves at least one index, and no index ever moves back. Opposite ends can do at most n − 1 moves before the indexes meet. Slow/fast does exactly n moves of fast. No nested loop, no extra list, so O(n) time and O(1) extra space.

Common bugs

Do

  • Loop while left < right when the two indexes must be different.
  • Sort first (O(n log n)) or use a hash set when the list is not sorted.
  • Move exactly one index after a mismatch.
  • Handle the empty and one-item lists before you start.
  • In slow/fast, return the new length and compare with the last kept value, nums[slow - 1].

Don't

  • Use left <= right for a pair: the two indexes can land on the same item.
  • Run the opposite-ends scan on an unsorted list: the move rule depends on order.
  • Move both indexes after a mismatch, which can skip the answer.
  • Forget that len(nums) - 1 is −1 or 0 for those tiny lists.
  • Return the list instead of the new length, or compare with the wrong neighbour.

Key points

  • Two indexes over one list turn an O(n²) pair search into one O(n) pass with O(1) extra memory.
  • Opposite ends needs order: a small sum moves left up, a big sum moves right down.
  • Slow/fast compacts in place: fast reads everything, slow writes what you keep.
  • Indexes only move forward (or inward), never back. That is why it is linear.
  • State the invariant, then check left < right, sortedness and the tiny lists.

Sources