Two pointers

Walk two indexes through an array, often from both ends towards the middle, to solve pair and partition problems in one O(n) pass instead of O(n²).

Description

Many array problems look like they need to compare every pair of elements, which is O(n²). The two-pointer technique uses some structure in the data, usually that it's sorted, to rule out most pairs without checking them.

The classic example: find two numbers in a sorted array that add up to a target. Put one pointer at the start and one at the end. If their sum is too small, move the left pointer right (the only way to increase it). If it's too large, move the right pointer left. Each step discards a whole row or column of candidate pairs, so the search takes at most n steps.

Other variants move both pointers in the same direction at different speeds: removing duplicates in place, merging two sorted arrays, partitioning around a pivot (as in quicksort), or detecting a cycle in a linked list with a slow and a fast pointer.

How it works

1031426384115146177LR

Pointers at both ends of a sorted array

  1. index 0: 1
  2. index 1: 3
  3. index 2: 4
  4. index 3: 6
  5. index 4: 8
  6. index 5: 11
  7. index 6: 14
  8. index 7: 17
Pointers at both ends of a sorted array

Step through: find two values that add up to 25

1031426384115146177LR

Step 1 of 6Find two values that add up to 25. Start with one pointer at each end.

0 comparisons

Complexity

OperationAverageWorst
Pair with a target sum (sorted input)O(n)O(n)
Same, if the input must be sorted firstO(n log n)O(n log n)
Brute force over all pairsO(n²)O(n²)

Space: O(1)

For unsorted input where sorting isn't allowed, a hash set gives O(n) time for the pair-sum problem, at the cost of O(n) memory.

TypeScript implementation

Pair sum with pointers from both ends, and in-place deduplication with a slow and a fast pointer.

two-pointers.ts
// Two classic two-pointer techniques on arrays.

/** Indexes of two values in a sorted array that add up to target, or null. */
export function pairWithSum(sorted: number[], target: number): [number, number] | null {
  let left = 0;
  let right = sorted.length - 1;
  while (left < right) {
    const sum = sorted[left] + sorted[right];
    if (sum === target) return [left, right];
    if (sum < target) left++; // need a bigger sum
    else right--; // need a smaller sum
  }
  return null;
}

/** Removes duplicates from a sorted array in place; returns the new length. */
export function dedupe(sorted: number[]): number {
  if (!sorted.length) return 0;
  let slow = 0; // last unique value written
  for (let fast = 1; fast < sorted.length; fast++) {
    if (sorted[fast] !== sorted[slow]) sorted[++slow] = sorted[fast];
  }
  return slow + 1;
}

export function demo(): string[] {
  const a = [1, 3, 4, 6, 8, 11, 14, 17];
  const p = pairWithSum(a, 25);
  const dupes = [1, 1, 2, 3, 3, 3, 5, 8, 8];
  const n = dedupe(dupes);
  return [
    `pair summing to 25: ${p ? `${a[p[0]]} + ${a[p[1]]}` : "none"}`,
    `pair summing to 2: ${pairWithSum(a, 2) ?? "none"}`,
    `deduped: [${dupes.slice(0, n).join(", ")}]`,
  ];
}

When to use it

Use it when

  • The input is sorted, or can be, and you're looking for pairs or triples with some property.
  • Merging or comparing two sorted sequences.
  • In-place array transformations: removing duplicates, partitioning, reversing.

Avoid it when

  • The data is unsorted and you can't sort it: use a hash set for pair problems.
  • You need all pairs, not one: the output itself is O(n²).

Pitfalls

  • Applying it to unsorted data, where moving a pointer doesn't reliably increase or decrease the sum.
  • Off-by-one stopping conditions: use left < right so an element isn't paired with itself.
  • Duplicates, which produce repeated answers unless you skip equal values.

Alternatives

Hash set

Choose it when the data isn't sorted and you have memory to spare.

Sliding window

Choose it when you're looking for the best contiguous range rather than a pair.

Binary search

Choose it when you fix one element and search for its partner, giving O(n log n).