DSA · Beginner · Pattern 2 of 11
Two Pointers
12 problems.
Your progress0%
- 1st Visit
- 0/12
- 2nd Visit
- 0/12
- Revise
- 0/12
About this pattern
Two pointers keeps two indices that move through a sequence according to a rule, so that every step discards candidates that cannot be optimal. The common forms are opposite ends moving inward (sorted pair sums, palindromes, partitioning) and a slow and a fast index moving in the same direction (in-place filtering, merging sorted arrays).
Look for a sorted or sortable array, a request for a pair or triplet with a target sum, or a need to compare elements from both ends without extra memory. Because each pointer only moves forward, the scan is O(n) after any O(n log n) sort, with O(1) extra space.
// Opposite ends on a sorted array: find a pair with sum == target.
int lo = 0, hi = (int)a.size() - 1;
while (lo < hi) {
long long s = (long long)a[lo] + a[hi];
if (s == target) break; // found the pair (lo, hi)
if (s < target) ++lo; // need a larger sum
else --hi; // need a smaller sum
}