Skip to lesson

The two pointers idea

Whenever a brute-force solution uses two nested loops (for i and for j) to compare pairs or compact elements in an array, ask whether i and j really need to reset on every iteration. The two pointers pattern coordinates two index variables so each pointer moves only in one direction, collapsing O(n²) work into a single O(n) pass.

One loop instead of two

Two pointers is a technique that moves two indexes through an array, often from both ends or at different speeds, to solve a problem in O(n) instead of O(n^2).

In Java, a pointer in an array or string problem simply means an int index variable such as left, right, read, or write.

Java
int[] nums = {1, 3, 4, 6, 9};int target = 13;int left = 0, right = nums.length - 1;  // two int "pointers"while (left < right) {    int sum = nums[left] + nums[right];    if (sum == target) break;           // 4 + 9 after only 3 steps    if (sum < target) left++;           // neither pointer ever moves back    else right--;}

In a naive nested loop, for each of the n positions of i, the inner index j scans up to n positions from scratch, performing roughly (n(n-1))/2 = O(n²) comparisons.

The two-pointers insight is to use information from the current comparison to eliminate an entire row or column of pairs at once. Instead of resetting j back to i + 1, each step advances at least one of the two pointers by 1 toward its goal. Because each pointer can move at most n times before the loop ends, the total number of iterations is at most 2n = O(n) time with O(1) auxiliary space.

  • Brute force: j resets for every i, costing O(n²) steps.
  • Two pointers: neither pointer ever backs up, costing at most 2n = O(n) steps.
  • Space: only two int index variables are needed (O(1) extra memory).

Pointers from both ends versus the same direction

Most two-pointer algorithms use one of three setups: pointers from both ends, pointers moving the same way, or one pointer in each of two arrays.

  1. Ask: am I comparing opposite ends / pairs in a sorted order? Choose converging pointers (left = 0, right = n - 1).
  2. Ask: am I filtering or compacting an array in place while keeping order? Choose same-direction pointers (write = 0, read = 0..n-1).
  3. Ask: am I combining two separate sorted inputs? Choose one pointer per array (i = 0, j = 0).

Example 1 · Brute force: square every value, then sort (O(n log n) time, O(n) space)

SortedSquaresBrute.javaJava
import java.util.Arrays;
public class SortedSquaresBrute {    public static int[] sortedSquares(int[] nums) {        int[] result = new int[nums.length];        for (int i = 0; i < nums.length; i++) {            result[i] = nums[i] * nums[i];        }        Arrays.sort(result);        return result;    }
    public static void main(String[] args) {        int[] nums = {-7, -3, 2, 3, 11};        System.out.println("Input:   " + Arrays.toString(nums));        System.out.println("Squares: " + Arrays.toString(sortedSquares(nums)));    }}
Output
Input:   [-7, -3, 2, 3, 11]
Squares: [4, 9, 9, 49, 121]

What this code does

  • Every value is squared, then Arrays.sort puts the squares in order. It is correct and short.
  • The cost is the sort: O(n log n) time. It ignores that the input was already sorted, which means the biggest squares can only be at the two ends.

Example 2 · Optimal: converging pointers fill the result from the back (O(n) time, O(n) space)

SortedSquaresDemo.javaJava
import java.util.Arrays;
public class SortedSquaresDemo {    // Input is sorted: [-7, -3, 2, 3, 11]    // Largest squares sit at the two extreme ends!    public static int[] sortedSquares(int[] nums) {        int n = nums.length;        int[] result = new int[n];        int left = 0;        int right = n - 1;        int pos = n - 1; // Fill result from largest to smallest
        while (left <= right) {            int leftSq = nums[left] * nums[left];            int rightSq = nums[right] * nums[right];            if (leftSq > rightSq) {                result[pos--] = leftSq;                left++;            } else {                result[pos--] = rightSq;                right--;            }        }        return result;    }
    public static void main(String[] args) {        int[] nums = {-7, -3, 2, 3, 11};        System.out.println("Input:   " + Arrays.toString(nums));        System.out.println("Squares: " + Arrays.toString(sortedSquares(nums)));    }}
Output
Input:   [-7, -3, 2, 3, 11]
Squares: [4, 9, 9, 49, 121]

What this code does

  • Squaring each element and calling Arrays.sort would take O(n log n) time.
  • Because negative numbers have their largest squares on the far left and positive numbers have their largest squares on the far right, converging pointers left and right fill result from back to front in one O(n) pass.
  • Why it is faster: the largest square is always at one of the two ends, so one comparison fixes one final position. n comparisons replace a full sort.

Example 3 · Same-direction pointers: compacting non-negative numbers in place

SameDirectionDemo.javaJava
import java.util.Arrays;
public class SameDirectionDemo {    // Keep only non-negative numbers at the front in their original order    // Returns the new logical length    public static int keepNonNegative(int[] nums) {        int write = 0;        for (int read = 0; read < nums.length; read++) {            if (nums[read] >= 0) {                nums[write] = nums[read];                write++;            }        }        return write;    }
    public static void main(String[] args) {        int[] data = {4, -1, 0, -9, 7, 2, -3};        int len = keepNonNegative(data);        System.out.println("Kept count: " + len);        System.out.println("Valid prefix: " + Arrays.toString(Arrays.copyOf(data, len)));    }}
Output
Kept count: 4
Valid prefix: [4, 0, 7, 2]

What this code does

  • The input is NOT sorted, and we must preserve the original left-to-right order [4, 0, 7, 2].
  • read visits every element once; write marks the next slot in the compacted prefix, finishing in O(n) time and O(1) space.
  1. Opposite ends (converging pointers): left = 0 starts at the first index and right = n - 1 at the last. The loop runs while (left < right) (or left <= right). Use this for symmetry problems (palindrome checking, array reversal) and sorted pair/extremum problems (pair sum, squaring a sorted array, container with most water).
  2. Same direction (read/write or fast/slow pointers): Both write = 0 and read = 0 start at index 0. read scans every element while write advances only when a condition is met. Use this for in-place array compaction (removing duplicates, moving zeros, filtering a value while keeping relative order).
  3. Two separate sequences: i = 0 points into array a and j = 0 points into array b. At each step you advance whichever pointer holds the smaller element. Use this for merging sorted arrays or finding sorted intersections.

When the data must be sorted (and when sorting breaks the problem)

Converging pointers rely on a monotonic order to decide which pointer to move.

Example 4 · Why converging pair-sum requires sorted data

SortingRequirementDemo.javaJava
import java.util.Arrays;
public class SortingRequirementDemo {    public static boolean hasPairWithSumTwoPointers(int[] nums, int target) {        int left = 0;        int right = nums.length - 1;        while (left < right) {            int sum = nums[left] + nums[right];            if (sum == target) {                return true;            } else if (sum < target) {                left++;            } else {                right--;            }        }        return false;    }
    public static void main(String[] args) {        int[] unsorted = {2, 8, 1, 5}; // 2 + 8 = 10 exists!        System.out.println("On unsorted [2,8,1,5] for target 10: " + hasPairWithSumTwoPointers(unsorted, 10));
        int[] sorted = Arrays.copyOf(unsorted, unsorted.length);        Arrays.sort(sorted); // [1, 2, 5, 8]        System.out.println("On sorted   [1,2,5,8] for target 10: " + hasPairWithSumTwoPointers(sorted, 10));    }}
Output
On unsorted [2,8,1,5] for target 10: false
On sorted   [1,2,5,8] for target 10: true

What this code does

  • On unsorted [2, 8, 1, 5], the first check 2 + 5 = 7 < 10 increments left past 2, permanently missing the pair 2 + 8 = 10.
  • After sorting into [1, 2, 5, 8], 1 + 8 = 9 < 10 moves left to 2, and 2 + 8 = 10 finds the valid pair.

For example, in a sorted array nums = [1, 3, 4, 7, 10], if nums[left] + nums[right] is too small, moving left++ is guaranteed to increase (or keep equal) the sum, and moving right-- is guaranteed to decrease (or keep equal) the sum. On an unsorted array [7, 1, 10, 3, 4], moving left++ could make the sum jump up or down unpredictably, so converging pair-sum fails unless you sort first.

However, you cannot blindly sort the input if the problem asks you to return original array indices (because sorting scrambles positions, unless you store (value, originalIndex) pairs in O(n) space) or if the problem is about contiguous subarrays of an unsorted array. By contrast, symmetry checks (like palindromes) and same-direction compaction (like moving zeros) do not require sorted data.

If sorting is allowed and takes O(n log n) time, sorting + an O(n) two-pointer pass still runs in O(n log n) overall — vastly faster than O(n²) brute force.

How to spot this pattern

Look for these clues in the problem statement.

  • The array is sorted (or may be sorted) and you need a pair, a triplet or a closest value: use pointers from both ends.
  • The task must be done in place with O(1) extra space and the order kept (remove, compact, move zeros): use a read pointer and a write pointer.
  • Two sorted arrays or lists must be merged or intersected: use one pointer in each.
  • The statement checks symmetry (palindrome, mirror, reverse): compare from both ends and move inward.

Next step

Check your understanding

10 quick questions