All algorithms
Searching

Two Pointers

Close in from both ends of a sorted array — O(n) instead of O(n²).

TimeO(n)SpaceO(1)CategorySearching

The two-pointer technique places one index at each end of a sorted array and moves them toward each other. To find a pair summing to a target: if the current sum is too small move the left pointer right, if it is too large move the right pointer left. Each step eliminates one candidate permanently.

It replaces the obvious O(n²) double loop with a single O(n) pass, and the same idea powers container-with-most-water, three-sum, palindrome checks and merging sorted ranges.

The insight is why moving a pointer is safe — the discarded element cannot pair with anything remaining. AlgoLens shows both pointers on the array so you can see the search space shrink from both sides.

The code

two_pointers.cpp
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> a = {1, 2, 4, 6, 8, 11};
    int target = 14;
    int lo = 0, hi = a.size() - 1;

    while (lo < hi) {
        int sum = a[lo] + a[hi];
        if (sum == target) break;
        if (sum < target) lo++;
        else hi--;
    }

    cout << lo << ' ' << hi << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Two Pointers

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going