⚡ Play a quiz
HomeLearnData Structures & AlgorithmsArrays › Two pointers
Lesson 3 of 5 · Arrays

The Two Pointer Technique in Arrays

Arrays60%

Two pointers turns a nested loop into a single pass. Instead of trying every pair — O(n2) — you keep two indices and move exactly one of them per step, using a property of the data to decide which. On a sorted array that property is order, and it collapses the problem to O(n).

Read time
9 min
Track
Data Structures & Algorithms
Sections
3
Practice
5

Converging pointers

Start one pointer at each end. Compare what they give you against the target, then move the pointer that can possibly improve the situation. Because the array is sorted, moving left right can only increase the sum, and moving right left can only decrease it — so each step eliminates a whole row of the pair matrix.

Dry run: arr = [8, 17, 42, 63, 99], target = 80
StepleftrightsumDecision
10 → 84 → 99107107 > 80, so the sum must shrink → move right inwards
20 → 83 → 637171 < 80, so the sum must grow → move left inwards
31 → 173 → 6380Match — return indices (1, 3)
Two sum on a sorted array
int[] twoSumSorted(int[] a, int target) {
    int left = 0, right = a.length - 1;
    while (left < right) {
        int sum = a[left] + a[right];
        if (sum == target) return new int[]{left, right};
        if (sum < target) left++;    // need a bigger sum
        else               right--;  // need a smaller sum
    }
    return new int[]{-1, -1};
}

Each iteration moves one pointer inwards and they never cross back, so the loop runs at most n times: O(n) time, O(1) space, against O(n2) for the nested-loop version.

arr = [8, 17, 42, 63, 99] target = 80 817 4263 99 left right Step 1: 8 + 99 = 107 > 80 → the sum must shrink so 99 cannot pair with anything → move right in 817 4263 99 Step 2: 8 + 63 = 71 < 80 → the sum must grow → move left in Step 3: 17 + 63 = 80 → found, in 3 steps instead of 10 comparisons
Each step eliminates a whole row of candidate pairs, not one pair — which is what turns the nested loop into a single pass.

The fast / slow variant

The second flavour puts both pointers at the start and moves them at different speeds, or moves the trailing one only under a condition. This is the read/write pair from the previous lesson, and it is how in-place filtering works.

Remove duplicates from a sorted array, in place
int removeDuplicates(int[] a) {
    if (a.length == 0) return 0;
    int slow = 0;                                 // last unique element
    for (int fast = 1; fast < a.length; fast++) {
        if (a[fast] != a[slow]) {
            a[++slow] = a[fast];                  // keep the new value
        }
    }
    return slow + 1;                              // new length
}

When two pointers applies

  • The array is sorted, or sorting it first does not break the question.
  • You are looking for a pair or a triple that satisfies a comparison.
  • You need to partition or filter in place with O(1) extra space.
  • You are working from both ends — palindrome checks, container-with-most-water, reversal.
Common mistake

Moving both pointers at once

Advancing left and right in the same iteration skips candidate pairs and quietly produces wrong answers on some inputs. Exactly one pointer moves per step, and the comparison decides which.

Common mistake

Using the wrong loop condition

while (left < right) excludes pairing an element with itself. Use <= only when a single middle element is a legitimate answer, such as in binary search.

Key takeaways

  • Two pointers replaces a nested loop with one pass when order lets you rule out candidates.
  • Converging: one pointer at each end, move the one that can improve the result.
  • Fast/slow: both start left, the trailing pointer marks where the next kept element goes.
  • O(n) time, O(1) space — and the sort, if you add one, dominates at O(n log n).

Practice

ProblemPatternLevel
Two sum on a sorted arrayConverging pointersEasy
Valid palindrome, ignoring non-alphanumericsConverging pointersEasy
Container with most waterConverging pointersMedium
Three sumSort + two pointersMedium
Trapping rain waterConverging pointersHard

Frequently asked questions

When should I use the two pointer technique?

When the array is sorted (or can be sorted) and you are searching for a pair, a triple, or a partition. The order lets each comparison eliminate many candidates at once instead of one at a time.

Does the array have to be sorted for two pointers?

For the converging variant, effectively yes — the decision about which pointer to move depends on order. The fast/slow variant works on unsorted arrays because it filters rather than compares against a target.

What is the difference between two pointers and sliding window?

A sliding window is a two-pointer variant where the pointers both move forward and the span between them is the answer. Converging two pointers move towards each other and the span shrinks.

Test yourself on Arrays

Reading is not recall. Take a timed quiz on this topic solo, or share a room code and battle friends on it.

⚡ Start the Arrays quiz

More in Arrays