Lesson 14 · Core algorithms

Two Pointers Technique

Two pointers are two indexes that move through a sequence by a rule, instead of a nested loop that tries every pair. Each move rules out values for good, so the whole scan is O(n). The skill is knowing why a move is safe.

Two Pointers Technique concept diagramA visual explanation of the layout and operations shown in this lesson.move two positions inward according to the comparison14681215LRsorted order tells us which pointer can safely move
1

Why Two Indexes Beat a Nested Loop

The two pointer technique keeps two indexes into an array or string and moves them by a rule. A nested loop looks at all n(n − 1)/2 pairs. With two pointers, each index moves at most n times and never backwards, so the total work is O(n).

The saving does not come from checking pairs faster. It comes from not checking most pairs at all. Every move rules out a group of candidates for good, and the method is only correct if you can show that none of them could have been the answer.

So for each pattern below, ask one question: what does this move throw away, and why is that safe? Answer that and you can rebuild the code in an exam instead of remembering it.

  • Each pointer moves at most n times: O(n)
  • Every move rules out candidates permanently
  • Correctness = a reason each move is safe
2

Converging Pointers

  1. Set L = 0 and R = n − 1
  2. While L < R, compare a[L] + a[R] with the target
  3. Too small: L += 1. Too big: R −= 1. Equal: return (L, R)
  4. If L meets R, no pair exists

Converging pointers start at the two ends, L at the first index and R at the last, and move toward each other until they meet. This form nearly always needs sorted input, because sorting is what tells you which pointer to move.

Pair sum is the standard example. In a sorted array, compare a[L] + a[R] with the target. If the sum is too small, a[L] cannot be in any answer: it is already paired with the largest value left and still falls short, so L moves right. If the sum is too big, a[R] is already paired with the smallest value left and is still too big, so R moves left. If it matches, you are done. Each check rules out one value, so at most n − 1 checks.

The same shape solves other problems with a different rule. A palindrome check compares the two ends and fails on a mismatch. Reversing an array swaps the ends and steps inward. In container with most water the area is limited by the shorter wall, so moving the taller wall can never help; the shorter side always moves.

If the input is unsorted, the rule can cross out half of the answer and miss it. Sorting first costs O(n log n) and loses the original indexes, unless you sort (value, index) pairs. When the indexes matter, a hash set gives pair sum in O(n) without sorting.

  • Start at both ends; stop when they meet
  • Too small: move L; too big: move R
  • Needs sorted input; otherwise sort first or use a hash set
  • Fixing one value and converging on the rest (3Sum), three-way splits and merging from the back: advanced two pointers
3

Same Direction Two Pointers

With same direction two pointers, both indexes start on the left and move right at their own pace. The most common form gives them different jobs: read visits every element, and write marks where the next kept element goes.

That is how you filter an array in place. Scan with read; whenever an element should stay, copy it to a[write] and move write on. At the end, the first write slots are the result and the rest is left-over data. One pass, O(n) time and O(1) extra space.

It handles remove-an-element, remove duplicates from a sorted array, and move zeros to the end. Deleting one element at a time would shift the tail on every delete, O(n²) in the worst case. Writing while scanning is safe because write never passes read: every slot being overwritten has already been read.

To keep each value at most k times, compare the incoming element with a[write − k] instead of a[write − 1]; the rest of the loop stays the same.

The sliding window is the other same direction form. There the two pointers mark the ends of a range: right grows it, and left moves only to fix a condition right broke. Neither moves back, so it is O(n) too, even though the code has a loop inside a loop.

  • read visits everything; write marks the next kept slot
  • In-place filtering in O(n) time, O(1) space
  • write ≤ read, so overwriting is always safe
  • A sliding window is the same idea with the pointers as range ends
Key reference

Terms, operations, and practical uses

Pointer roles

  • L and RThe left and right indexes in converging pointers; L only moves right, R only moves left.
  • Read pointerVisits every element once, left to right, and decides what to keep.
  • Write pointerThe next slot for a kept element; never ahead of the read pointer.

Why it is correct

  • Ruled-out valueA value that cannot be in any answer, shown before its pointer moves past it.
  • Loop conditionConverging loops run while L < R; when they meet, every pair has been ruled in or out.
  • Sorted preconditionMoving L right raises the sum and moving R left lowers it only when the array is sorted.

Costs

  • O(n) scanEach pointer moves at most n times and never back.
  • O(n log n) with sortingSorting first dominates; a hash set can be faster when the input is unsorted.
  • O(1) spaceOnly two indexes are stored; in-place filtering needs no second array.
Implementation

Code in Python, C++ and Java

def reverse_array(arr):
    left, right = 0, len(arr) - 1
    while left < right:
        arr[left], arr[right] = arr[right], arr[left]
        left += 1
        right -= 1
letters = ['a', 'b', 'c', 'd', 'e']
reverse_array(letters)
print(letters)
#include <iostream>
#include <vector>
using namespace std;

void reverseArray(vector<char>& arr) {
    int left = 0, right = arr.size() - 1;
    while (left < right) {
        swap(arr[left], arr[right]);
        left++;
        right--;
    }
}

int main() {
    vector<char> letters = {'a', 'b', 'c', 'd', 'e'};
    reverseArray(letters);
    cout << '[';
    for (size_t i = 0; i < letters.size(); i++) {
        if (i) cout << ", ";
        cout << '\'' << letters[i] << '\'';
    }
    cout << "]\n";
}
public class Main {
    static void reverseArray(char[] arr) {
        int left = 0, right = arr.length - 1;
        while (left < right) {
            char temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        char[] letters = {'a', 'b', 'c', 'd', 'e'};
        reverseArray(letters);
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < letters.length; i++) {
            if (i > 0) sb.append(", ");
            sb.append('\'').append(letters[i]).append('\'');
        }
        System.out.println(sb.append("]"));
    }
}
Watch it run

Step through it

Running on [2, 3, 5, 8, 11, 13, 17] target 16 and 31 · [11, 2, 13, 5] target 7 · [1, 1, 2, 2, 2, 3, 5, 5]

pair sum: target 1620315283114135176LR2 + 17 = 19checks: 1 of 21 pairssorted order tells us which pointer to move
Step 1

Sorted array, target 16

Find two values that add up to 16. Checking every pair would take 7 × 6 / 2 = 21 sums. Instead, put L on the smallest value and R on the largest. Because the array is sorted, moving L right can only make the sum bigger, and moving R left can only make it smaller.

Output
1 / 11
4

Choosing a Two Pointer Pattern

A third family moves two pointers through the same linked list at different speeds, one step and two steps, to find the middle node or detect a loop. It needs no sorting and no indexes; fast and slow pointers covers it, including why the two must meet.

To decide whether two pointers fit at all, look for two signs: the data is sorted, or can be sorted without losing what you need; and the answer involves a pair, a range or an in-place rewrite. If a pointer would ever need to move back to an earlier position, the O(n) argument breaks and a different method is needed.

The three patterns
PatternStartNeedsTypical use
ConvergingBoth endsSorted dataPair sum, palindrome, container with most water
Same directionBoth on the leftNothing specialRemove duplicates, move zeros, sliding window
Fast and slowBoth at the headA chain to followMiddle of a list, loop detection
  • Sorted data + a pair: converging
  • In-place filter or a range: same direction
  • Linked list middle or loop: fast and slow
  • Pointers that must move back: not a two pointer problem