Arrays & Hashing · Pattern 5 of 26

Two pointers

Two indexes that only move forward (or toward each other), so the whole scan is O(n). Opposite ends for sorted pairs and palindromes; a read and a write pointer for in-place edits; one pointer per sequence for comparing.

6 variations · 37 problems · 5 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • A sorted array and a pair condition
  • Palindromes, reversing, or comparing from both ends
  • Remove or move elements in place with O(1) extra space
  • Walk two strings or arrays side by side

The template

Two Pointer
// opposite ends: is there a pair with this sum? (sorted input)
boolean hasPairWithSum(int[] a, int target) {
    int i = 0, j = a.length - 1;
    while (i < j) {
        int s = a[i] + a[j];
        if (s == target) return true;
        if (s < target) i++;           // need a bigger sum
        else j--;                      // need a smaller sum
    }
    return false;
}

// read / write pointers: remove duplicates from a sorted array in place
int removeDuplicates(int[] a) {
    int w = 0;                         // a[0..w) is the answer so far
    for (int r = 0; r < a.length; r++)
        if (w == 0 || a[r] != a[w - 1]) a[w++] = a[r];
    return w;
}

The variations

  1. 1Opposite ends on sorted data

    Start at both ends. The sum (or area, or weight) tells you which side to move: the move that cannot be part of a better answer. Sort first when the order of the answer does not matter.

  2. 2Palindromes and reversing

    Compare or swap from both ends, moving inward. Skip characters that do not count; allow one mismatch by trying both skips.

  3. 3Read and write pointers (in place)

    The read pointer scans everything; the write pointer marks where the next kept element goes. Everything before the write pointer is the answer so far.

    Worked example Move Zeroes Easy Read the solution
  4. 4One pointer per sequence

    Walk two strings or arrays together, advancing whichever pointer the comparison allows. Subsequences, typed-with-long-press and abbreviations all work this way.

  5. 5Walk runs: up, down, gaps

    Move a pointer while a condition holds (going up, same value, empty seat), then measure the run. Mountains, ranges and gaps between people are runs.

  6. 6More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Using opposite-end pointers on an unsorted array: the "move the smaller side" logic only works when the order means something.
  • Moving both pointers when only one should move.
  • For merge-in-place problems, writing from the front and overwriting values you still need. Write from the back.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.