Two Pointers Basics

How two positions moving through the data replace a loop inside a loop, worked out on one small sorted array.

Two pointers means walking through an array or string with two positions at once instead of one. Picture two people checking a row of numbered boxes, one starting from each end, who compare what they see and then decide which of them steps forward. Questions that seem to need every pair of elements, one loop inside another, can often be answered in a single pass this way.

Every idea below is worked out on the same small sorted array, nums = [1, 3, 3, 4, 6, 9].

Ruling out many pairs with one check

Do two numbers in nums add up to 13? The plain way tries every pair: 1 with 3, 1 with the second 3, 1 with 4, and so on. Six numbers make 15 pairs, and exactly one of them, 4 and 9, adds up to 13. In general n numbers make n(n - 1) / 2 pairs, so the work grows with the square of the length.

The array is sorted, and that lets one check say a lot. Keep two index variables: left starts at index 0, on the 1, and right starts at index 5, on the 9. An index variable used like this is what the word pointer means here; it simply points at a position in the array.

Four rows, check 1 to check 4, on the array 1, 3, 3, 4, 6, 9 with target 13. The left pointer moves from index 0 to 3 while the right pointer stays on the 9; at check 4 the sum is 13 and the pair is found.

Look at the row labelled check 1. The sum of the boxes marked left and right is 1 + 9 = 10, which is too small. The 9 is the largest value in the array, so the 1 plus any other value is at most 10. No pair that uses this 1 can reach 13, so all five of its pairs are ruled out by one check, and left moves one place to the right.

Check 2 and check 3 both find 3 + 9 = 12, still too small, so each 3 is ruled out the same way. The cells the left pointer has passed are greyed out. At check 4 the sum is 4 + 9 = 13, and the pair is found after 4 checks instead of up to 15.

That is the whole idea behind every two-pointer solution: a pointer moves past an element only when you can say why that element can no longer be part of the answer.

Opposite ends: one pointer at each end

What if the sum is too big? Then the value under right is too big for every partner, because the value under left is the smallest one still in play, so right moves one place to the left. The two pointers walk toward each other until they find a pair or meet.

Ask for 8 instead of 13. Check 1 finds 1 + 9 = 10, too big, so the 9 is ruled out. Check 2 finds 1 + 6 = 7, too small, so the 1 goes. Check 3 finds 3 + 6 = 9, check 4 finds 3 + 4 = 7, and check 5 finds the second 3 plus 4, again 7. Now both pointers sit on index 3. A pair needs two different positions, so the loop runs only while left < right, and it stops after 5 checks with no pair. That answer is right: no two numbers in nums add up to 8.

This shape fits when the answer is about a pair and the two ends have an order you can reason about. A sorted array is the usual case. Checking whether a word reads the same backwards is another: compare the first and last letters, then step both pointers inward.

Same direction: a read pointer and a write pointer

Now a different question on the same array: keep one copy of each value, in place, without a second array. Both pointers start near the front and move forward. The read pointer visits every element once. The write pointer marks where the next kept value goes, so the cells before it, nums[0 .. write - 1], always hold the values kept so far.

The first value is always kept, so write starts at 1 and read starts at index 1. Because the array is sorted, a repeat always equals the last kept value, nums[write - 1], so that is the one comparison needed.

Five rows, read = 1 to read = 5, showing 1, 3, 3, 4, 6, 9 after each step. The orange cells are the kept part. The second 3 is skipped, and 4, 6 and 9 are copied forward to indexes 2, 3 and 4.

Each row of the picture shows the array after one step, with the kept part in orange. In the row labelled read = 1, the 3 differs from the last kept value 1, so it is copied to index 1 and write moves to 2. In the row labelled read = 2, the second 3 repeats the last kept value and is skipped, so write stays put while read moves on.

From then on every value is new, and each one moves one place to the left: the 4 is copied to index 2, the 6 to index 3 and the 9 to index 4. The kept part ends as [1, 3, 4, 6, 9], and write is 5, the number of values kept. Look at the last cell, though: it still holds the old 9, because nothing was ever written there.

A sliding window also moves two pointers in the same direction. There the stretch between them, the window, is what matters, such as the sum of the numbers inside it.

Fast and slow: two speeds on a chain

Some data is not read by index but by following links. Suppose the five kept values 1, 3, 4, 6 and 9 are stored in a chain of small objects, called nodes. Each node holds one value and a link named next to the node after it. A chain like this is a linked list.

Now suppose a bug makes the 9 link back to the 4 instead of ending the list. Code that follows next until it runs out would loop forever. How can a program notice that the links go round in a circle, a cycle, without remembering every node it has seen?

The chain 1, 3, 4, 6, 9 with 9 linking back to 4. A table shows slow and fast per round: start 1 and 1, round 1 at 3 and 4, round 2 at 4 and 9, round 3 both at 6.

Start two pointers on the first node. In each round, slow moves one link and fast moves two. Read the table on the right of the picture: after round 1 the slow pointer is on 3 and the fast one on 4, and after round 2 they are on 4 and 9. In round 3 the fast pointer goes from 9 back to 4 and on to 6, and the slow one also lands on 6.

Why must they meet? Once both are inside the circle 4, 6, 9, the fast pointer gains one link on the slow one each round, so the gap between them shrinks by one until it is zero. Without a cycle the fast pointer reaches the end of the list, and the loop stops there.

One pointer per input

When a problem has two sorted arrays or two strings, each gets its own pointer. Take the kept values [1, 3, 4, 6, 9] and a second sorted array [2, 5], and merge them into one sorted array. A pointer i starts on the 1 and a pointer j on the 2. Each step copies the smaller of the two values and moves that pointer forward. After the 1 comes the 2, then the 3, the 4 and the 5. At that point the second array is used up, and the rest of the first array, 6 and 9, is copied as it is.

The four shapes in Java

The program below puts each shape into one method:

  • The method pairWithSum moves left and right toward each other and returns the two positions it finds, or an empty array.
  • The method removeDuplicates moves read over the array, copies each new value to write, and returns how many values it kept.
  • The method hasCycle moves slow and fast along a chain of Node objects and returns true when they land on the same node.
  • The method merge moves i and j over two sorted arrays and fills a new array, with k marking its next free place.

A helper, chain, builds a linked list from an array of values and, when asked, links the last node back to an earlier one. The main method runs every walk-through above on nums, plus an empty array, an array of three equal values, a chain without a cycle, a chain of one node, and a merge with an empty array.

Java
import java.util.Arrays;

public class TwoPointers {

    // Opposite ends: positions of two values in a sorted array that add up to target.
    static int[] pairWithSum(int[] sorted, int target) {
        int left = 0;
        int right = sorted.length - 1;
        while (left < right) {
            int sum = sorted[left] + sorted[right];
            if (sum == target) {
                return new int[] {left, right};
            } else if (sum < target) {
                left++;                       // sorted[left] is too small for any partner
            } else {
                right--;                      // sorted[right] is too big for any partner
            }
        }
        return new int[0];                    // no pair found
    }

    // Same direction: keep one copy of each value in place, return how many are kept.
    static int removeDuplicates(int[] sorted) {
        if (sorted.length == 0) {
            return 0;
        }
        int write = 1;                        // sorted[0 .. write - 1] is the kept part
        for (int read = 1; read < sorted.length; read++) {
            if (sorted[read] != sorted[write - 1]) {
                sorted[write] = sorted[read];
                write++;
            }
        }
        return write;
    }

    // Fast and slow: does following next from head ever come back around?
    static boolean hasCycle(Node head) {
        Node slow = head;
        Node fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;                 // one step
            fast = fast.next.next;            // two steps
            if (slow == fast) {
                return true;
            }
        }
        return false;                         // fast ran off the end
    }

    // One pointer per input: merge two sorted arrays into one sorted array.
    static int[] merge(int[] a, int[] b) {
        int[] out = new int[a.length + b.length];
        int i = 0;
        int j = 0;
        int k = 0;
        while (i < a.length && j < b.length) {
            out[k++] = a[i] <= b[j] ? a[i++] : b[j++];
        }
        while (i < a.length) {
            out[k++] = a[i++];
        }
        while (j < b.length) {
            out[k++] = b[j++];
        }
        return out;
    }

    static class Node {
        int value;
        Node next;
        Node(int value) {
            this.value = value;
        }
    }

    // Builds a chain from the values; loopTo >= 0 makes the last node point back there.
    static Node chain(int[] values, int loopTo) {
        Node[] nodes = new Node[values.length];
        for (int i = 0; i < values.length; i++) {
            nodes[i] = new Node(values[i]);
            if (i > 0) {
                nodes[i - 1].next = nodes[i];
            }
        }
        if (loopTo >= 0) {
            nodes[values.length - 1].next = nodes[loopTo];
        }
        return nodes[0];
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, 3, 4, 6, 9};

        System.out.println("pair for 13: " + Arrays.toString(pairWithSum(nums, 13)));
        System.out.println("pair for 8: " + Arrays.toString(pairWithSum(nums, 8)));
        System.out.println("pair in []: " + Arrays.toString(pairWithSum(new int[0], 5)));

        int[] copy = nums.clone();
        int kept = removeDuplicates(copy);
        System.out.println("kept " + kept + ": " + Arrays.toString(Arrays.copyOf(copy, kept)));
        int[] same = {2, 2, 2};
        kept = removeDuplicates(same);
        System.out.println("kept " + kept + ": " + Arrays.toString(Arrays.copyOf(same, kept)));

        int[] unique = Arrays.copyOf(copy, 5);
        System.out.println("cycle 9 -> 4: " + hasCycle(chain(unique, 2)));
        System.out.println("no cycle: " + hasCycle(chain(unique, -1)));
        System.out.println("one node: " + hasCycle(chain(new int[] {7}, -1)));

        System.out.println("merged: " + Arrays.toString(merge(unique, new int[] {2, 5})));
        System.out.println("merged with []: " + Arrays.toString(merge(new int[0], unique)));
    }
}

Running it prints:

Output
pair for 13: [3, 5]
pair for 8: []
pair in []: []
kept 5: [1, 3, 4, 6, 9]
kept 1: [2]
cycle 9 -> 4: true
no cycle: false
one node: false
merged: [1, 2, 3, 4, 5, 6, 9]
merged with []: [1, 3, 4, 6, 9]

The line pair for 13: [3, 5] gives positions, not values: index 3 holds the 4 and index 5 holds the 9, the pair from check 4. For 8 the result is empty, as the five checks showed. On an empty array right starts at -1, so the loop never runs and nothing is read out of bounds.

The line kept 5: [1, 3, 4, 6, 9] matches the last row of the read and write picture, and [2, 2, 2] shrinks to a single 2. The chain where 9 links back to 4 reports true; the same chain ending at 9 and the one-node chain report false, because the fast pointer runs out of links first. The last two lines show that the merge handles an empty input by copying the other array.

Spotting a two-pointer problem

Which shape does a new problem need? A few signs point the way:

  • The input is sorted, or may be sorted, and the question is about a pair or a triple of values: one pointer at each end.
  • The question is whether a string reads the same backwards, or asks you to reverse something in place: one pointer at each end.
  • The task says to remove, move or compact elements in place while keeping the order of the rest: a read pointer and a write pointer.
  • The data is a chain of links, or an array whose values point to other indexes, and the question is about a cycle: fast and slow.
  • There are two sorted arrays or two strings to compare or combine: one pointer per input.
  • The question asks for the longest or shortest stretch of neighbouring elements that meets a condition: a sliding window.

Traps

What goes wrong most often? Each slip below shows up on nums or on the chain built from its kept values.

Letting the pointers meet. Change the loop in pairWithSum to left <= right and ask for 8 again. After the same five checks both pointers stand on index 3, and the loop now runs a sixth check: 4 + 4 = 8. The method reports a pair, but it used the single 4 twice. Keep left < right when the two values must come from different positions.

Reading past the kept part. After removeDuplicates, printing the whole array gives [1, 3, 4, 6, 9, 9]. The old 9 in the last cell is still there, as the read and write picture shows. Only the first write cells are the answer, which is why the method returns that count and main prints Arrays.copyOf(copy, kept).

Checking too little before a double step. The fast pointer reads fast.next.next, so both fast and fast.next must exist. A loop that checks only fast.next != null still stops on the chain 1, 3, 4, 6, 9 without the back link, but on the four-node chain 1, 3, 4, 6 it throws NullPointerException. After one round the fast pointer is on the 4. The next double step takes it past the 6 to the end of the list, so it holds null, and the loop check then asks null for its next.

Complexity

All four shapes share one property: no pointer ever returns to a place it has already passed.

  • Time: O(n) for opposite ends and for read and write, because each check ends the search or moves one pointer one place, and in an array of n elements the pointers have at most n places to cover. When the input must be sorted first, the sort adds O(n log n).
  • Time: O(n) for fast and slow on a chain of n nodes, because without a cycle the fast pointer reaches the end within n / 2 rounds. With a cycle, the slow pointer enters it within n rounds, and the gap then closes by one link per round.
  • Time: O(n + m) for merging an array of n values with one of m values, because each step copies one of the n + m values into the output.
  • Space: O(1) for the first three shapes, since they keep only two positions and work on the input itself, and O(n + m) for the merge, which needs the new array.

Where to go next

Pairs from both ends of sorted data:

Read and write in one array:

Fast and slow, and one pointer per input: