Two Pointers
Two indexes instead of repeated searching
The two-pointers technique uses two indexes that move through an array according to a rule. It is especially useful when the position of one pointer helps determine how the other should move, allowing us to avoid checking every possible pair of elements.
A simple example is checking whether an array is a palindrome. One pointer starts on the left, the other on the right, and then they move toward each other.
int left = 0;
int right = numbers.length - 1;
boolean palindrome = true;
while (left < right) {
if (numbers[left] != numbers[right]) {
palindrome = false;
break;
}
left++;
right--;
}
Each element participates in at most one pair comparison, so this algorithm runs in O(n) time and uses O(1) extra space.
Pointers can move in different ways
Two pointers do not have to start at opposite ends. Sometimes both move from left to right: one reads elements, while the other marks the position where the next suitable element should be written. This pattern often appears when filtering data directly inside the original array.
int write = 0;
for (int read = 0; read < numbers.length; read++) {
if (numbers[read] != 0) {
numbers[write] = numbers[read];
write++;
}
}
After the loop, the first write cells contain all nonzero elements
in their original order. The read pointer explores the array,
while write marks the next free position of the result.
left, right,
read, or write represents.
If their roles are clear in words, the loop condition and movement rule usually become clearer too.