Two Pointers

Two indexes walk through an array, string or linked list, and each move rules out many answers at once. It often turns an O(n²) pair search into one O(n) pass with O(1) extra space.

Overview

A brute-force pair search checks every pair with two nested loops, which is O(n²). The two-pointer technique keeps two indexes instead and moves one of them on each step. Each move is safe because the structure of the input (sorted order, or a rule about what to keep) proves that the skipped pairs cannot be the answer. So the whole input is walked once.

Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.

The four shapes

The rule: the shapes differ only in where the two pointers start and in the rule that moves them.

  • Opposite ends: the pointers start at the first and last index and move toward each other. Two Sum II, Container With Most Water and palindrome checks use this shape.
  • Read and write: both pointers start at the beginning. The read pointer moves every step, and the write pointer moves only when a value is kept. Remove Duplicates, Move Zeroes and Remove Element use it.
  • Fast and slow: both pointers start at the head of a linked list. Slow moves 1 node per step and fast moves 2. Linked List Cycle and finding the middle of a list use it.
  • Two inputs: there is one pointer per input, and the pointer at the smaller value moves. Merging two sorted arrays and Is Subsequence use it.

Sliding window is a close relative where the two pointers mark the ends of a range; it has its own topic. The rest of this chapter takes the shapes one at a time, starting with opposite ends, where the reason a move is safe is easiest to see.

> [!TIP] > If the array is not sorted and the question wants indexes, sorting would lose them. A hash map is usually the better tool there.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio