The Two-Pointer Technique

Two fingers on a list

Many problems become easy if you keep two positions (pointers) at once and move them step by step – often one from each end.

Think of it like this: Checking if a word reads the same backwards: one finger on the first letter, one on the last. Compare, then move both inward.

#include <iostream>
#include <string>
using namespace std;

bool isPalindrome(const string& s) {
    int left = 0, right = (int)s.size() - 1;
    while (left < right) {
        if (s[left] != s[right]) return false;
        left++;
        right--;
    }
    return true;
}

int main() {
    cout << isPalindrome("racecar") << " " << isPalindrome("cpp") << endl;
    return 0;
}

Output

1 0

Pair with a target sum (sorted)

Checking every pair is O(n²). On a sorted vector two pointers do it in O(n):

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> v = {1, 3, 4, 6, 8, 11};
    int target = 10;
    int left = 0, right = (int)v.size() - 1;
    while (left < right) {
        int s = v[left] + v[right];
        if (s == target) {
            cout << v[left] << " + " << v[right] << " = " << target << endl;
            break;
        }
        if (s < target) left++;     // need a bigger sum
        else right--;               // need a smaller sum
    }
    return 0;
}

Output

4 + 6 = 10

Remember: Two pointers works best on sorted data, or when you compare both ends of something.

HOME LABS COMMUNITY DASHBOARD