Two Pointers

Two indices moving through a sequence — from both ends or in the same direction — to replace O(n²) pair searches with O(n).

Beginner 2 min readLesson 2 of 25 Interview Q&A

The two pointers pattern uses two indices that move through the data according to a rule. It turns many O(n²) "check every pair" problems into a single O(n) pass.

When to use this pattern
  • The input is sorted (or can be sorted) and you need a pair / triplet meeting a condition.
  • You must modify an array in place (remove duplicates, move zeros, partition).
  • You compare elements from both ends (palindromes, container with most water).
  • You merge or compare two sorted sequences.

Variant 1: opposite ends

Start L at the beginning and R at the end. Each step, look at the pair and move whichever pointer can only improve things. Every move discards possibilities that provably can't be the answer.

InteractiveTwo pointers — find a pair summing to 19
1
0
L
3
1
4
2
6
3
8
4
11
5
14
6
17
7
R
1 + 17 = 18 < 19 → need bigger sum → move L right
1/7
Two Sum II (sorted input)
int[] twoSumSorted(int[] a, int target) {
    int l = 0, r = a.length - 1;
    while (l < r) {
        int sum = a[l] + a[r];
        if (sum == target) return new int[]{l, r};
        if (sum < target) l++;      // need a bigger sum
        else r--;                   // need a smaller sum
    }
    return new int[]{-1, -1};
}

Why it's correct: if a[l] + a[r] < target, then a[l] paired with anything left of r is even smaller — so a[l] can never be part of the answer and is safely discarded.

3Sum: fix one, two-pointer the rest

Sort, then for each i run two pointers on the suffix for target −a[i]. Skip equal neighbours to avoid duplicate triplets. O(n²).

3Sum
List<List<Integer>> threeSum(int[] a) {
    Arrays.sort(a);
    List<List<Integer>> res = new ArrayList<>();
    for (int i = 0; i < a.length - 2; i++) {
        if (i > 0 && a[i] == a[i - 1]) continue;          // skip duplicate anchors
        int l = i + 1, r = a.length - 1;
        while (l < r) {
            int s = a[i] + a[l] + a[r];
            if (s < 0) l++;
            else if (s > 0) r--;
            else {
                res.add(List.of(a[i], a[l], a[r]));
                while (l < r && a[l] == a[l + 1]) l++;    // skip duplicates
                while (l < r && a[r] == a[r - 1]) r--;
                l++; r--;
            }
        }
    }
    return res;
}

Variant 2: same direction (read / write pointers)

A fast pointer scans every element; a slow pointer marks where the next kept element should be written. Used for in-place filtering.

10112223343546writeread
Remove duplicates in place: 'write' marks the end of the unique prefix.
Remove duplicates from a sorted array / move zeros
int removeDuplicates(int[] a) {
    if (a.length == 0) return 0;
    int w = 1;                                   // next write position
    for (int r = 1; r < a.length; r++)
        if (a[r] != a[w - 1]) a[w++] = a[r];
    return w;                                    // new length
}

void moveZeroes(int[] a) {
    int w = 0;
    for (int r = 0; r < a.length; r++)
        if (a[r] != 0) { int t = a[w]; a[w++] = a[r]; a[r] = t; }
}

Variant 3: two sequences

One pointer per input: merging two sorted arrays, checking whether one string is a subsequence of another, intersecting sorted lists.

Container with most water (opposite ends, greedy move)
int maxArea(int[] h) {
    int l = 0, r = h.length - 1, best = 0;
    while (l < r) {
        best = Math.max(best, Math.min(h[l], h[r]) * (r - l));
        if (h[l] < h[r]) l++; else r--;     // move the shorter wall: it limits the area
    }
    return best;
}
Practice problems
  • Valid Palindromeends inward, skip non-alphanumericseasy
  • Two Sum II – Input Array Is Sortedeasy
  • Remove Duplicates from Sorted Arrayread/writeeasy
  • Move Zeroeseasy
  • Squares of a Sorted Arrayfill result from the backeasy
  • 3Sumsort + fix onemedium
  • 3Sum Closestmedium
  • Container With Most Watermove the shorter wallmedium
  • Sort Colorsthree pointers (Dutch flag)medium
  • 4Summedium
  • Trapping Rain Watertrack leftMax/rightMaxhard
Key takeaways
  • Opposite-end pointers on sorted data: each move discards impossible candidates → O(n).
  • Read/write pointers filter arrays in place with O(1) extra space.
  • k-Sum = sort + fix k−2 elements + two pointers: O(n^(k−1)).
  • Skip equal neighbours to avoid duplicate results.
Interview questions
QTwo pointers vs hash map for Two Sum — which and when?easy

Unsorted input and indices needed: a hash map, O(n) time and space. Already sorted (or you only need values): two pointers, O(n) time and O(1) space. Sorting first costs O(n log n) and loses original indices.

QTrapping rain water in O(1) space.hard

Two pointers with leftMax and rightMax. Move the side with the smaller max: water above that position is sideMax − height, because the other side is guaranteed to have a taller wall. O(n), O(1).