Video in progress

Strong Junior 🧠 Problem solving

When does the two pointers technique work? Show it with removing duplicates from a sorted array in place.

It works when the data is sorted, or when walking from both ends makes sense. For duplicates, the slow pointer marks where the next unique value gets written, and the fast pointer marks the element being read. O(n) time, O(1) memory.

📖 Answer

Two pointers has two main shapes: from both ends toward each other (palindrome, a pair with a given sum in a sorted array) and in one direction at different speeds (filtering, removing duplicates).

An example of the second: [1, 1, 2, 3, 3, 3, 4] → at the start [1, 2, 3, 4], length 4.

static int dedupe(int[] a) {
    if (a.length == 0) return 0;
    int write = 1;                  // the next unique value goes here
    for (int read = 1; read < a.length; read++) {
        if (a[read] != a[write - 1]) {
            a[write++] = a[read];
        }
    }
    return write;
}

This is where sortedness does the work: equal values sit next to each other, so comparing with the last written one is enough. On an unsorted array this logic breaks, and you'd need a HashSet there.

The same idea solves the variant "each value may stay at most twice": you compare with a[read] != a[write - 2].