Algorithms · 368 words · 2 minute read

Java Two Pointers: When It Works, Why It Works, and Practice

By · Published 2026-09-04 · Updated 2026-09-04

Two pointers is not a trick for every array problem. It is useful when two positions can move monotonically and each move permanently rules out some work. That is why it appears in reversing an array, scanning a palindrome, and searching a sorted array for a target sum. Before writing it, say what each pointer means and what part of the input has already been handled.

Start with an invariant

For an in-place reverse, the values outside left and right are already in their final positions. For a sorted two-sum search, every pair excluded by a pointer move is provably too small or too large. An invariant turns pointer updates into reasoning rather than guesswork. Write it in a comment, then trace an input with four elements.

public class Main {
    static void reverse(int[] values) {
        for (int left = 0, right = values.length - 1; left < right; left++, right--) {
            int temporary = values[left];
            values[left] = values[right];
            values[right] = temporary;
        }
    }
    public static void main(String[] args) {
        int[] values = {1, 2, 3, 4};
        reverse(values);
        for (int value : values) System.out.print(value + " ");
    }
}

The output is 4 3 2 1. Each iteration makes two elements final, so the loop stops when the pointers meet or cross.

Sorted input changes the decision

In a sorted two-sum problem, compare the values at both ends. If their sum is too small, moving the right pointer cannot help because it selects an equal or smaller value; move left instead. If the sum is too large, move right. This proof depends on sorted order. On an unsorted array, use a HashMap or sort a copy while preserving original indices.

Common mistakes

  • Moving both pointers after every comparison, which skips candidates.
  • Using left <= right when the two positions must refer to distinct elements.
  • Calling a sorted-input algorithm on arbitrary input.
  • Forgetting that a method that swaps values mutates its argument.

Practice in sequence

Begin with reverse an array, where the invariant is visible. Then solve pair with sum using a map and compare it with a sorted two-pointer version. Finish with container with most water, where moving the shorter wall is the key proof. Use the array compiler examples to test empty, one-element, duplicate, and negative-value inputs.

Continue with the Java practice path · Try code in the Java compiler