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
The array is sorted, and that lets one check say a lot. Keep two index variables: leftright
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
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 rightleftright
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 < rightnums
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 readwritenums[0 .. write - 1]
The first value is always kept, so writereadnums[write - 1]
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 writewriteread
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]write
A
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
Now suppose a bug makes the 9 link back to the 4 instead of ending the list. Code that follows next
Start two pointers on the first node. In each round, slowfast
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][2, 5]ij
The four shapes in Java
The program below puts each shape into one method:
- The method
movespairWithSum andleft toward each other and returns the two positions it finds, or an empty array.right - The method
movesremoveDuplicates over the array, copies each new value toread , and returns how many values it kept.write - The method
moveshasCycle andslow along a chain offast objects and returns true when they land on the same node.Node - The method
movesmerge andi over two sorted arrays and fills a new array, withj marking its next free place.k
A helper, chainmainnums
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:
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]right
The line kept 5: [1, 3, 4, 6, 9][2, 2, 2]truefalse
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
Letting the pointers meet. Change the loop in pairWithSumleft <= rightleft < right
Reading past the kept part. After removeDuplicates[1, 3, 4, 6, 9, 9]writemainArrays.copyOf(copy, kept)
Checking too little before a double step. The fast pointer reads fast.next.nextfastfast.nextfast.next != nullNullPointerExceptionnext
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:
Two Sum II, Input Array Is Sorted is the pair search from both ends as a full problem, returning the positions of the two values.3Sum fixes one number and runs the pair search on the rest, skipping repeats.Container With Most Water moves the shorter of two walls, with no sorting at all.Squares of a Sorted Array fills the output from the back, because the largest squares sit at the two ends.
Read and write in one array:
Remove Duplicates From Sorted Array is the read and write walk as a full problem, with the two pointers named fast and slow.Move Zeroes keeps the non-zero values in order and fills the rest with zeros.
Fast and slow, and one pointer per input:
Find the Duplicate Number treats array values as links and finds where the cycle starts.Backspace String Compare walks two strings from the back, one pointer each.Long Pressed Name matches a typed string against a name, letting extra presses of the same key through.