Two Pointers

Basic Algorithms
≈ 2 min read

Two indexes instead of unnecessary passes

The two-pointers technique works with strings just as naturally as it does with arrays. One index can start on the left, the other on the right, and at each step the algorithm decides which one should move next.

Because String is immutable, simply moving indexes over the original string is enough for inspection. If characters must actually be rearranged, the string can temporarily be represented as a char[].

Moving toward each other

For example, a string can be reversed by swapping symmetric positions. Each pair is processed once.

char[] chars = text.toCharArray();
int left = 0;
int right = chars.length - 1;

while (left < right) {
    char temp = chars[left];
    chars[left] = chars[right];
    chars[right] = temp;

    left++;
    right--;
}

String reversed = new String(chars);

The left pointer moves right and the right pointer moves left, so the loop performs roughly half as many iterations as the string length. The time complexity is still O(n). The additional array is required here because String is immutable, while the pointer logic itself uses O(1) extra memory.

Pointers do not have to move in the same way

In more interesting problems, one pointer may stay in place while the other searches for a suitable character, or one of them may skip positions that do not participate in the comparison. The main idea is not symmetric movement, but that each index has a clear role and does not move backward without a reason.

Define the meaning of each pointer first. For example: “left is the first unprocessed position from the left,” and “right is the first unprocessed position from the right.” Then the loop condition and the moments when each pointer moves become much easier to understand.